Skip to content

Commit cde2d34

Browse files
authored
Merge pull request xianhu#32 from wuhongyewhy/master
使用with自动关闭文件
2 parents da93a3b + ffebb22 commit cde2d34

File tree

1 file changed

+4
-0
lines changed

1 file changed

+4
-0
lines changed

python_base.py

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -320,6 +320,10 @@ def __missing__(self, key):
320320
fp.truncate([size]) # 把文件裁成规定的大小,默认的是裁到当前文件操作标记的位置。
321321
for line in open('data'):
322322
print(line) # 使用for语句,比较适用于打开比较大的文件
323+
with open('data') as file:
324+
print(file.readline()) # 使用with语句,可以保证文件关闭
325+
with open('data') as file:
326+
lines = file.readlines() # 一次读入文件所有行,并关闭文件
323327
open('f.txt', encoding = 'latin-1') # Python3.x Unicode文本文件
324328
open('f.bin', 'rb') # Python3.x 二进制bytes文件
325329
# 文件对象还有相应的属性:buffer closed encoding errors line_buffering name newlines等

0 commit comments

Comments
 (0)