Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

使用with自动关闭文件 #32

Merged
merged 1 commit into from
May 30, 2018
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions python_base.py
Original file line number Diff line number Diff line change
Expand Up @@ -320,6 +320,10 @@ def __missing__(self, key):
fp.truncate([size]) # 把文件裁成规定的大小,默认的是裁到当前文件操作标记的位置。
for line in open('data'):
print(line) # 使用for语句,比较适用于打开比较大的文件
with open('data') as file:
print(file.readline()) # 使用with语句,可以保证文件关闭
with open('data') as file:
lines = file.readlines() # 一次读入文件所有行,并关闭文件
open('f.txt', encoding = 'latin-1') # Python3.x Unicode文本文件
open('f.bin', 'rb') # Python3.x 二进制bytes文件
# 文件对象还有相应的属性:buffer closed encoding errors line_buffering name newlines等
Expand Down