python里面对文件的读写操作
以下內容轉自:http://www.cnblogs.com/qi09/archive/2012/02/10/2344964.html和http://blog.csdn.net/xiaoqi823972689/article/details/12945769
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 lineline= 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.
另外,列表里面的元素類型必須是字符串類型,這樣才能寫入文件。
總結
以上是生活随笔為你收集整理的python里面对文件的读写操作的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: PyQt4基本布局常用方法之addSpa
- 下一篇: PyQt的QTableWidget的全面