1、
- 已打开的文本文件里的内容可以用read方法来读取。如:
file=open('filename.txt','r')
cont=file.read()
print (cont)
file.close()
- 如果仅仅读取文件的一部分,可以调用read方法并传递一个参数,这个参数决定了读取的字节数。采用上述方法可以一点一点的读取文件内容,而调用不带参数的read时则返回文件中剩余的内容。如:
file=open('filename.txt','r')
print file.read(10)
print file.read(10)
print file.read(10)
print file.read()
file.close()
- 在读取出文件中所有内容后,任何进一步读取操作都会返回一个空字符串,这是因为这时的操作是在文件末尾进行的,如:
file=open('filename.txt','r')
file.read()
print 'Re_reading'
print file.read()
print 'Finished'
file.close()
执行结果:
>>>
Re-reading
Finished
>>>
- 为了读取文件中的每一行,可以使用readlines函数,该函数返回一个列表,列表中的每一项是文件中的每一行,如:
file=open('filename.txt','r')
print file.read()
file.close()
执行结果:
>>>
['Line 1 text\n','Line 2 text\n','Line 3 text']
>>>
或者,也可以用for循环来迭代文件的各行,如:
file=open('filename.txt','r')
for line in file:
print line
file.close()
执行结果:
>>>
Line 1 text
Line 2 text
Line 3 text
>>>