python对文件的读操作用read,readline,readlines。
read可以接受一个变量以限制每次读取的数量。read每次读取整个文件,并将文件内容以字符串形式存储。(见下面的例子)
对于连续的面向行的处理,它是不必要的,如果文件大于内存,该方法也不可行。
readline和readlines较为相似,它们之间的差异是readlines一次读取整个文件,像read一样。readlines自动将文件内容按行处理成一个列表。
另一方面,readline每次只读取一行,通常比readlines慢很多,仅当没有足够内存可以一次读取整个文件时,才会用readline
看一下实例:
以fortext.txt文本为例:
#coding=utf-8
fo =open("H:/fortext.txt","r")
#case1
#print type(fo.readlines()) 输出结果为list类型
for line in fo.readlines():
print line
#case2
line = fo.readline()
#print type(fo.readline()) 输出结果为str类型
print line
while line:
print line
line= fo.readline()
#print type(fo.read()) 输出结果为str类型
最后的输出结果都是:
对文件的写操作有write和writelines,(没有WriteLine)
先用一个小小的例子来看看write和writelines到底是什么
fi = open(r"H:/text.txt",'a+') #a+表示打开一个文件用于读写。如果该文件已存在,
# 文件指针将会放在文件的结尾。文件打开时会是追加模式。
#如果该文件不存在,创建新文件用于读写。(text.txt文件还并未存在)
#fi.write("123");fi.seek(0,0);print fi.read()
#fi.writelines("123");fi.seek(0,0);print fi.read()
分别执行write和writelines,发现结果都是
writelines并不多加一个换行
百度之后发现;
百度‘write writelines python’第一条的结果是:
Use the write() function to write a fixed sequence of characters -- called a string -- to a file. You cannot use write() to write arrays or Python lists to a file. If you try to use write() to save a list of strings, the Python interpreter will give the error, "argument 1 must be string or read-only character buffer, not list."
write函数可以用来对文件写入一个字符串,但不能使用write 对文件写入一个数组或者list,如果你企图使用write对文件写入一个字符串list表单,Python将报错
即如果写成
#write和writelines
fi = open(r"H:/text.txt",'a+') #a+表示打开一个文件用于读写。如果该文件已存在,
# 文件指针将会放在文件的结尾。文件打开时会是追加模式。
#如果该文件不存在,创建新文件用于读写。(text.txt文件还并未存在)
#fi.write("123");fi.seek(0,0);print fi.read() #必须加fi.seek;否则会因为fi.read函数而读入乱码
#fi.writelines("123");fi.seek(0,0);print fi.read()
fi.write(['1','2','3'])
这样的话就会报错。
继续查看百度,
The writelines() function also writes a string to a file. Unlike write(), however, writelines can write a list of strings without error. For instance, the command nameOfFile.writelines(["allen","hello world"]) writes two strings "allen" and "hello world" to the file foo.txt. Writelines() does not separate the strings, so the output will be "allenhello world."writelines同样是对文件写入一个字符串,但是跟write不同的是,writelines可以操作list字符串。比如, 输入命令 offile.writelines(["allen","hello world"]) 将两个字符串"allen" and "hello world" 同时写入了文件foo.txt中。但writelines 并没有分开这些字符串,输出应该是"allenhello world."
如果将上面的fi.write修改成fi.writelines,文件里面就会写入123.
另外,列表里面的元素类型必须是字符串类型,这样才能写入文件。