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
'python' 카테고리의 다른 글
python csv와 excel export 하는방법 및 엑셀 export 속도 빠르게 하는방법 (0) | 2018.04.23 |
---|---|
python 인스턴스 클래스가 담겨진 list 특정 변수값으로 정렬하기 (0) | 2018.04.18 |
inconsistent use of tabs and spaces in indentation 에러 해결 (0) | 2018.03.27 |
파이썬3.6 [datetime] 날짜 시간 처리 모듈 (0) | 2018.02.22 |
python 공부하기 좋은 사이트 (0) | 2018.01.09 |