본문 바로가기
python

with 문

by 이농이능 2018. 1. 15.

With Statement


You can also work with file objects using the with statement. It is designed to provide much cleaner syntax and exceptions handling when you are working with code. That explains why it’s good practice to use the with statement where applicable. 

One bonus of using this method is that any files opened will be closed automatically after you are done. This leaves less to worry about during cleanup. 

To use the with statement to open a file:

 

with open(“filename”) as file: 

 

Now that you understand how to call this statement, let’s take a look at a few examples.

 

with open(“testfile.txt”) as file:  
data = file.read() 
do something with data 

 

You can also call upon other methods while using this statement. For instance, you can do something like loop over a file object:

 

with open(“testfile.txt”) as f: 
for line in f: 
print line, 

 

You’ll also notice that in the above example we didn’t use the “file.close()” method because the with statement will automatically call that for us upon execution. It really makes things a lot easier, doesn’t it?



출처 http://www.pythonforbeginners.com/files/reading-and-writing-files-in-python