2017-01-12 2 views
0

Ich habe vergessen, wie oft ich die Datei geöffnet, aber ich brauche sie zu schließen Ich habe die txt.close und txt_again.close, nachdem ich es mindestens 2 mal Geschlossene Dateien schließen?

geöffnet

Ich folge Zed A. Shaw Python Das Lernen Hard Way

#imports argv library from system package 
from sys import argv 
    #sets Variable name/how you will access it 
script, filename = argv 
    #opens the given file from the terminal 
txt = open(filename) 
    #prints out the file name that was given in the terminal 
print "Here's your file %r:" % filename 
    #prints out the text from the given file 
print txt.read() 
txt.close() 
#prefered method 
    #you input which file you want to open and read 
print "Type the filename again:" 
    #gets the name of the file from the user 
file_again = raw_input("> ") 
    #opens the file given by the user 
txt_again = open(file_again) 
    #prints the file given by the user 
print txt_again.read() 
txt_again.close() 

Antwort

4

um solche Dinge zu verhindern, ist es besser, immer die Datei zu öffnen Context Manager with wie:

with open(my_file) as f: 
    # do something on file object `f` 

auf diese Weise brauchen Sie nicht zu befürchten es explizit zu schließen.

Vorteile:

  1. Bei Ausnahme innerhalb with angehoben, um die Datei zu schließen kümmern Python wird.
  2. Keine Notwendigkeit, die close() explizit zu erwähnen.
  3. Viel besser lesbar, wenn man den Umfang/die Verwendung der geöffneten Datei kennt.

Siehe: PEP 343 -- The "with" Statement. Überprüfen Sie auch Trying to understand python with statement and context managers, um mehr über sie zu erfahren.

Verwandte Themen