python文件讀寫操作

python中,可以通過open()函數打開一個文件創建一個file類的對象來操作文件,也可以在打開文件創建file對象時指定文件打開的模式(如果沒有指定打開模式,默認爲r),來決定能對文件進行的操作。這裏說的文件讀寫操作就是利用file類中提供的read、readline、readlines和write等方法來操作文件。

1、read和write

read([size]) -> read at most size bytes, returned as a string.
If the size argument is negative or omitted, read until EOF is reached. Notice that when in non-blocking mode, less data than what was requested may be returned, even if no size parameter was given.
write(str) -> None. 
Write string str to file. Note that due to buffering, flush() or close() may be needed before the file on disk reflects the data written.
read函數除非指定size,否則會默認讀取文件的全部內容並返回。write函數會將一個str寫入到文件當前寫入內容的末尾(意思就是,f.write(str1), f.write(str2),str2會出現在str1的後面)。

2、打開模式

和其它編程語言類似,python中的文件打開模式也有三種:讀模式('r')、寫模式('w')和追加模式(‘a’)。讀模式下打開的文件只能用來進行讀操作;寫模式下打開的文件能進行寫操作,但是文件中原來的內容會被清空掉;追加模式下打開的文件能進行寫操作,而且所有被寫入的內容都會追加在原來文件的末尾。

2.1 寫模式和追加模式

寫模式和追加模式下打開的文件如果不存在,該文件會默認被創建,其內容爲空。

(1) r mode: write to a file

$ cat file_w.py 
filename = "temp.txt"
f = open(filename,"w")
f.write("hello, world.\n")
f.write("hi, python!\n")
f.close()
$ python file_w.py 
$ cat temp.txt 
hello, world.
hi, python!
(2) r mode: write to the same file again
$ cat file_w.py 
filename = "temp.txt"
f = open(filename,"w")
f.write("Be serious!\n")
f.write("Not funny at all!\n")
f.close()
$ python file_w.py 
$ cat temp.txt 
Be serious!
Not funny at all!
可以看出,之前文件中的內容都被清空了。

(3) a mode: write to the same file

$ cat file_a.py 
filename = "temp.txt"
f = open(filename,"a")
f.write("hello, world.\n")
f.write("hi, python!\n")
f.close()
$ python file_a.py 
$ cat temp.txt 
Be serious!
Not funny at all!
hello, world.
hi, python!
2.2 讀模式

對於讀模式下打開的文件,可以進行讀取操作。如果讀取模式下打開一個不存在的文件,會報錯(IOError: [Errno 2] No such file or directory)。

(1) read

像上文中說的read默認讀取整個文件的內容並返回。

$ cat file_r.py 
filename = "temp.txt"
f = open(filename,"r")
print f.read()
f.close()
$ python file_r.py 
Be serious!
Not funny at all!
hello, world.
hi, python!
(2) readline

readline([size]) -> next line from the file, as a string.
Retain newline.  A non-negative size argument limits the maximum number of bytes to return (an incomplete line may be returned then).Return an empty string at EOF.
讀取文件的一行,保留換行符,到文件末尾返回空串。

$ cat file_readline.py 
filename = "temp.txt"
f = open(filename,"r")
line =  f.readline()
while line://最後的空行也會被打印出來
    #readline will retain an enter, so add ',' at the end to remove the enter of print
    print line,
    line = f.readline()
f.close()
$ cat temp.txt 
Be serious!
Not funny at all!
hello, world.
hi, python!
//這裏有一個空行
$ python file_readline.py 
Be serious!
Not funny at all!
hello, world.
hi, python!
//這裏最後也會打出空行
(3) readlines

readlines([size]) -> list of strings, each a line from the file.    
Call readline() repeatedly and return a list of the lines so read. The optional size argument, if given, is an approximate bound on the total number of bytes in the lines returned.
重複調用readline讀取文件中的所有行到一個list。

$ cat file_readlines.py 
filename = "temp.txt"
f = open(filename,"r")
lines =  f.readlines()
for line in lines:
    print line,
f.close()
$ cat temp.txt 
Be serious!
Not funny at all!
hello, world.
hi, python!
//這裏有一個空行
$ python file_readlines.py 
Be serious!
Not funny at all!
hello, world.
hi, python!
//這裏最後也會打出空行
好了,到這裏就可以用python進行文件的基本操作了,後面有複雜的需求會進一步補充。^_^
發佈了88 篇原創文章 · 獲贊 30 · 訪問量 26萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章