关闭文件:
# Open your file here
try:
# Write data to
your file
finally:
file.close()
也可以使用如下方法:
with open("somefile.txt") as
somefile:
do_something(somefile)
with实际上是context manager,它支持__enter__、__exit__方法。__enter__没有参数,返回值为as后面的变量,__exit__有3个参数:an exception type, an exception object, and an exception traceback。
基本的文件方法:
f.read()读取所有
>>> import pprint
>>>
pprint.pprint(open(r'c:\text\somefile.txt').readlines())
['Welcome to
this file\n',
'There is
nothing here except\n',
'This stupid
haiku']
§11.3 重复操作文件
f = open(filename)
char = f.read(1)
while char:
process(char)
char = f.read(1)
f.close()
另外一种方法:
f = open(filename)
while True:
char = f.read(1)
if not char: break
process(char)
f.close()
读取行:
f = open(filename)
while True:
line = f.readline()
if not line: break
process(line)
f.close()
列表的形式:
f = open(filename)
for char in f.read():
process(char)
f.close()
f = open(filename)
for line in f.readlines():
process(line)
f.close()
读取部分文件:
import fileinput
for line in fileinput.input(filename):
process(line)
老的版本使用xreadlines,现在被input代替了。
文件的迭代器:
f = open(filename)
for line in f:
process(line)
f.close()
由于python会自动关闭文件,甚至可以更简单:
for line in open(filename):
process(line)
import sys
for line in sys.stdin:
process(line)
>>> f = open('somefile.txt', 'w')
>>> f.write('First line\n')
>>> f.write('Second line\n')
>>> f.write('Third line\n')
>>> f.close()
>>> lines =
list(open('somefile.txt)')
>>> lines
['First line\n', 'Second line\n', 'Third
line\n']
>>> first, second, third =
open('somefile.txt')
>>> first
'First line\n'
>>> second
'Second line\n'
>>> third
'Third line\n'