From ffebb22b2856238fe52b73afc85c7b416e1181dc Mon Sep 17 00:00:00 2001 From: wuhongyewhy Date: Tue, 1 May 2018 10:27:27 +0800 Subject: [PATCH] =?UTF-8?q?=E4=BD=BF=E7=94=A8with=E8=87=AA=E5=8A=A8?= =?UTF-8?q?=E5=85=B3=E9=97=AD=E6=96=87=E4=BB=B6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- python_base.py | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/python_base.py b/python_base.py index ebd6999..34ba3a6 100644 --- a/python_base.py +++ b/python_base.py @@ -320,6 +320,10 @@ 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等