閱讀493 返回首頁    go 阿裏雲 go 技術社區[雲棲]


Python 中File I/O 和一些常用的方法

version:Python 3.3.2

Python用open()返回一個文件,最常用的open函數是open(filename , mode)

其中,mode包括有"w"(write), “r”(read) , “a”(open the file for appending), 當然也可以用“wt”表示寫入text,“rt”表示讀取text;

file.readline()可以一次讀取文件中內容的一行

* 每次文件操作完成之後,一定要加上file.close()函數將文件關閉。

>>> strings = """\I'm a great man who was born in China
I was born to give and give and give
This is a new line
And this is another new line"""
>>> file.write(strings)
123                  #此處表示寫入的內容總共有多少byte
>>> file.close()

我們可以調用read()函數將文件的內容打印出來,但是當read()之後,當前的位置將停留在末尾也就是文字的最後位置,如果這時候想再次打印文件內容,調用read()函數將得到空的內容,可行的辦法之一是將文件關閉再重新打開,當然我們也有一些新的辦法來簡化此操作。


>>> file = open("output.txt","rt")
>>> print(file.read())
\I'm a great man who was born in China
I was born to give and give and give
This is a new line
And this is another new line
>>> print(file.read())
#這裏將會是空白,因為此刻指針(光標)的位置處於段落末尾


1. seek()

seek可以用來改變當前object的位置(例如file read之後),通常的格式seek(offset, from_what)。

The position is computed from adding offset to a reference point; the reference point is selected by the from_what argument. A from_what value of 0 measures from the beginning of the file, 1 uses the current file position, and 2 uses the end of the file as the reference point. from_what can be omitted and defaults to 0, using the beginning of the file as the reference point.

默認隻有一個參數,就表示從文件開始的位置(0),因此,seek(0)就表示目前是處於文件的開頭,第二個參數表示從哪裏開始計算,0表示開頭,也是默認的,1表示當前位置,2表示末尾。

>>> file.seek(0)
0#當前位置
>>> print(file.read())
\I'm a great man who was born in China
I was born to give and give and give
This is a new line
And this is another new line

2. 利用list,將file中的文字存入到list中
file有一個函數readlines(),注意此函數和readline()有區別,readline是一次讀取一行,而readlines()是將所有數據存入list中,每一行作為list的一個element,如此之後,即便我們close的文件,依舊可以繼續打印文件裏已經存儲在list中的內容了。
>>> x = file.readlines()#錯誤,注意此時的位置已經處於末尾了
>>> print(x)
[]#所以打印出來的內容為空
>>> print(x[0])
Traceback (most recent call last):
  File "<pyshell#7>", line 1, in <module>
    print(x[0])
IndexError: list index out of range
>>> file.seek(0)#將位置置於開頭
0
>>> x = file.readlines()
>>> print(x)
["\\I'm a great man who was born in China\n", 'I was born to give and give and give\n', 'This is a new line\n', 'And this is another new line']
>>> print(x[0])#打印list的各項內容
\I'm a great man who was born in China
	
>>> file.close()#即便關閉了file,也可以繼續操作,因為內容已經存儲到了list中

>>> print(x[0])
\I'm a great man who was born in China

>>> print(x[3])
And this is another new line
>>> 
代碼中我犯了一個錯誤,第一次沒有將位置seek到開頭,所以第一次沒有將lines存入到x中,也就是說,若想把每一行存入到list中,也需要將當前位置置於0

最後更新:2017-04-03 16:59:42

  上一篇:go c++中的引用類型和const
  下一篇:go Java中關於i++與++i的問題