先来一个小例子:
import sys
dir= os.path.dirname(os.path.abspath(__file__))
file_path='%s/test.txt' % dir
f= open(file_path,'r')
#print f.read()
print "----------------"
for line in f.readlines():
line.strip()
print line
#f.write('testxxx3xx33333333333')
#print filet.read()
f.close()
输出结果为:
----------------
fucttttx3tttt22221111133
fucttttx3tttt22221111133
fucttttx3tttt22221111133
其实,python文件读入函数有read(), readline(), readlines() & xreadlines() func in Python
介绍如下:
* read(size) >> size is an optional numeric argument and this func returns a quantity of data equal to size. If size if omitted, then it reads the entire file and returns it
读入指定大小的内容,以byte为单位,size为读入的字符数,返回str类型
注意省略时,read()会读取整个文件,将读取到底的文件内容放到一个字符串变量,返回str类型。
* readline() >> reads a single line from file with newline at the end。
readline()读取一行内容,放到一个字符串变量,返回str类型。
* readlines() >> returns a list containing all the lines in the file
readlines() 读取文件所有内容,按行为单位放到一个列表中,返回list类型。
* xreadlines() >> Returns a generator to loop over every single line in the file
返回一个生成器,来循环操作文件的每一行。循环使用时和readlines基本一样,但是直接打印就不同
print f.xreadlines()
print f.readlines()
输出如下:
<open file '/home/deve_test_user/liu/test.txt', mode 'r' at 0x2b1e19035cd8>
['f3tttt22221111133\n', 'fucttttx3tttt22221111133\n', 'fucttttx3tttt22221111133\n', 'fucttttx3tttt22221111133\n', 'fucttttx3tttt22221111133\n', 'fucttttx3tttt22221111133\n', 'fucttttx3tttt22221111133\n', 'fttx3tttt2222111113endend\n']
所以二者类型不同。但使用时相同。