說明:
主要是file()和open()函數的使用,但在查open()函數的幫助時,會有下面的說明:
>>> help(open)
……
Open a file using the file() type, returns a file object.
因此,兩個函數其實都是一樣的,下面只用file()。
在列舉file()的作用時,使用help即是很好的方法,下面則是應重點關注的內容:
close(...)
| close() -> None or (perhaps) an integer. Close the file.
flush(...)
| flush() -> None. Flush the internal I/O buffer.
readline(...)
| readline([size]) -> next line from the file, as a string.
readlines(...)
| readlines([size]) -> list of strings, each a line from the file.
seek(...)
| seek(offset[, whence]) -> None. Move to new file position.
tell(...)
| tell() -> current file position, an integer (may be a long integer).
write(...)
| write(str) -> None. Write string str to file.
writelines(...)
| writelines(sequence_of_strings) -> None. Write the strings to the file.
xreadlines(...)
| xreadlines() -> returns self.
1.創建文件
--基本格式:
f = file('test.txt', 'w') f = write('Hello World!') f.close()
·w:寫模式,文件不存在就創建,存在則自動覆蓋原來的內容,只能寫,不能讀;
·w+:寫讀模式,但一開始還是會清空原來文件內容,只是在寫文件之後可以讀取;
·寫的內容放在內存當中,如果要寫入磁盤,可以f.close()關閉文件或f.flush()實時寫入磁盤;
·不可以實時改變模式,只能把文件關閉後,再次打開時定義模式;
--實例:
>>> f = file('test.txt', 'w') >>> f.write('Hello World!') >>> f.flush()
xpleaf@xpleaf-machine:~/seminar6/day2$ more test.txt Hello World!
--write()與writelines()
·前者寫入的內容只能是字符串,後者則可以寫入列表:
>>> f.write(['a', 'b', 'c']) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: expected a character buffer object >>> f.writelines(['a', 'b', 'c']) >>>
--f.close()的重要說明
·如果沒有f.close(),則在程序運行結束後,系統會自動幫我們關閉文件;
·長時間運行的程序,需要打開並編輯文件(如用'a'模式),沒有關閉文件,會導致文件內容無法保持一致性的問題(如果系統中有其他程序需要編輯該文件);
·Linux中的Vim編輯器自帶文件鎖定功能,即不能同時編輯同一文件;
·Python中文件的鎖是沒有加上的,需要開發者自行爲文件加鎖。
2.讀取文件與遍歷文件內容
--基本格式:
f = file('test.txt', 'r') ===>可以不加'r',默認就是該模式 f = read() f.close()
·r:默認;
·r+:讀寫模式,可以嘗試使用,每讀取一行,指針就跳到下一行,寫的時候,就直接覆蓋掉指針指的這一行;
·rb:在windows平臺下編輯的文件,在linux中用python進行讀取時,模式要選擇“rb”,否則有可能會出現亂碼的現象,即跨平臺的文件都要注意此點;
--read()、readline、readlines()與xreadlines()
·前三者都是直接把文件內容全部寫入內存當中,然後再全部讀取或一行一行地讀取;
·都採用迭代的方式讀取,即指針最開始指向第一行,讀取第一行後,指針指向下一行;
-read()
·把文件內容全部讀取:
>>> f = file('test.txt', 'r') >>> f.read() "Hello World!\nI'm xpleaf.\nNice to meet you!\n" >>> f.read() '' ===>內容已經讀完,即指針已經在最後一行,後面沒有內容 ·可以用tell()查看當前指針的位置: >>> f.tell() 43 ===>43,即是最後一個字符
·重新讀取文件內容,可以f.close()後再次打開,也可以使用f.seek(0):
>>> f.seek(0) ===>重新尋址,讓指針指向文件最開始 >>> f.tell() 0 >>> print f.read() Hello World! I'm xpleaf. Nice to meet you!
-readline()
·以字符串方式,一行一行地讀取文件內容:
>>> f.seek(0) >>> f.readline() 'Hello World!\n' >>> f.readline() "I'm xpleaf.\n" >>> f.readline() 'Nice to meet you!\n' >>> f.readline() ''
-readlines()
·以列表的方式,一行一行地讀取文件內容,一行即爲列表中的一個元素:
>>> f.seek(0) >>> f.readlines() ['Hello World!\n', "I'm xpleaf.\n", 'Nice to meet you!\n'] >>> f.readlines() []
·因此,習慣性的用法是:修改文件內容
>>> f.seek(0) >>> filelist = f.readlines() >>> print filelist ['Hello World!\n', "I'm xpleaf.\n", 'Nice to meet you!\n'] >>> filelist[2] = 'See you next time!' >>> print filelist ['Hello World!\n', "I'm xpleaf.\n", 'See you next time!']
·再以w的方式打開文件,用f.writelines(filelist)的方式寫入,即可實現修改文件內容的目的;
-xreadlines()
·不是先把文件內容全部寫入內存,而是每讀取一行才寫入一行,寫下一行時即對前面內存中的內容進行回收;
·在讀取較大文件時,適宜採用這種辦法。
--文件內容的遍歷:使用readlines()
>>> f = file('test.txt', 'r') >>> filelist = f.readlines() >>> for eachline in filelist: ... print eachline, ... Hello World! I'm xpleaf. Nice to meet you!
3.文件內容追加
--基本格式:
f = file('test.txt', 'a') f = write('Hello World!') f.close()
·文件內容追加到最後一行上,如果最後一行有'\n',則追加到下一行;
·write只能添加字符串,如果是數值或其它類型的數據類型,則需要使用str()進行轉換;
--實例:
>>> f = file('test.txt', 'a') >>> f.write('See you next time!') >>> f.write('I will miss you much!\n') >>> f.flush() xpleaf@xpleaf-machine:~/seminar6/day2$ cat test.txt Hello World! I'm xpleaf. Nice to meet you! See you next time!I will miss you much!
4.文件內容替換
--基本格式:
import fileinput for line in fileinput.input('filepath', inplace = 1): line = line.replace('oldtext', 'newtext') print line,
·inplace = 1,表示要修改文件內的內容,默認值爲0,表示不修改文件內容,加“print line,”時只打印內存中修改的內容(看下面例子);
·inplace = 1時,如果不加“print line,”,原來文件內容會爲空;
·可以額外加backup參數,表示在修改文件內容時進行備份;
--實例:
-正確操作:
>>> import fileinput >>> for line in fileinput.input('test.txt', inplace = 1, backup = '.ori'): ... line = line.replace('Hello World!', 'Hello, everyone!') ... print line, ...
xpleaf@xpleaf-machine:~/seminar6/day2$ ls -l test* -rw-rw-r-- 1 xpleaf xpleaf 87 9月 4 15:32 test.txt -rw-rw-r-- 1 xpleaf xpleaf 83 9月 4 15:19 test.txt.ori xpleaf@xpleaf-machine:~/seminar6/day2$ cat test.txt Hello, everyone! I'm xpleaf. Nice to meet you! See you next time!I will miss you much!
-如果沒有加inplace = 1時:
>>> for line in fileinput.input('test.txt'): ... line = line.replace('Nice', 'Well') ... print line, ... Hello, everyone! I'm xpleaf. Well to meet you! See you next time!I will miss you much! xpleaf@xpleaf-machine:~/seminar6/day2$ cat test.txt Hello, everyone! I'm xpleaf. Nice to meet you! See you next time!I will miss you much!
-如果沒有加“print line,”時:
>>> for line in fileinput.input('test.txt'): ... line = line.replace('Nice', 'Well') ... >>> for line in fileinput.input('test.txt', inplace = 1): ... line = line.replace('Hello', 'Hey') ... xpleaf@xpleaf-machine:~/seminar6/day2$ cat test.txt xpleaf@xpleaf-machine:~/seminar6/day2$ ===>文件內容已被清空