假如test.txt文件包含如下内容:
Welcome to this file
There is nothing here except
This stupid haiku
下面是基本读文件的方法:
# read(n) 指定参数
>>> f = open(r'I:\python\test.txt')
>>> f.read(7)
'Welcome'
>>> f.read(4)
' to '
>>> f.close()
# read() 不指定参数
>>> f = open(r'I:\python\test.txt')
>>> print f.read()
Welcome to this file
There is nothing here except
This stupid haiku
>>> f.close()
# readline()
>>> f = open(r'I:\python\test.txt')
>>> for i in range(3):
print str(i) + ':' + f.readline()
0:Welcome to this file
1:There is nothing here except
2:This stupid haiku
>>> f.close()
#readlines()
>>> import pprint
>>> pprint.pprint(open(r'I:\python\test.txt').readlines())
['Welcome to this file\n',
'There is nothing here except\n',
'This stupid haiku']
readline返回一行的字符串, readlines返回包含文件所有内容的字符串列表, 每个元素是一行的字符串。
pprint 模块的pprint方法将内容分成每个小项单行显示。
本文系转载,前往查看
如有侵权,请联系 cloudcommunity@tencent.com 删除。
本文系转载,前往查看
如有侵权,请联系 cloudcommunity@tencent.com 删除。