Python 檔案 I/O 2018-07-31

來源:互聯網
上載者:User

標籤:fse   cat   tsp   文本   std   列印   大小   imp   產生   

1. 列印到螢幕:print

可以給print傳遞零個或多個用逗號隔開的運算式,print把傳遞的運算式轉換成一個字串運算式,並將結果寫到標準輸出:

# -*- coding: UTF-8 -*-                                          print "Hello",",World",123
[email protected]:~/code$ python test.py Hello ,World 123
2. 讀取鍵盤輸入:raw_input input

2.1 raw_input([prompt])從標準輸入讀取一個行,並返回一個字串(去掉行尾的分行符號)

# -*- coding: UTF-8 -*-                                          str = raw_input("Please input:")print "What you input is :",str

輸出:

[email protected]:~/code$ python test.py Please input:hello worldWhat you input is : hello world

2.2 input([prompt])raw_input([prompt])函數基本類似,但是input可以接收一個Python運算式作為輸入,並將運算結果返回

# -*- coding: UTF-8 -*-                                          str = input("Please input:")print "What you input is :",str

輸出:

[email protected]:~/code$ python test.py Please input:helloTraceback (most recent call last):  File "test.py", line 2, in <module>    str = input("Please input:")  File "<string>", line 1, in <module>NameError: name ‘hello‘ is not defined
  • 可以看到像往常一樣輸入 hello 的結果是NameError,但輸入一個Python運算式則正常
[email protected]:~/code$ python test.py Please input:[x*5 for x in range(2,10,2)]What you input is : [10, 20, 30, 40]
3. 開啟和關閉檔案

3.1 open,首先必須用內建的open函數開啟一個檔案,建立一個file對象,相關方法才可以調用它進行讀寫
file object = open(file_name, [, access_mode][, buffering])
file_name:file_name變數是一個包含了你要訪問的檔案名稱的字串值。
access_mode:access_mode決定了開啟檔案的模式:唯讀,寫入,追加等。所有可取值見如下的完全列表。這個參數是非強制的,預設檔案訪問模式為唯讀(r)
buffering:如果buffering的值被設為0,就不會有寄存。如果buffering的值取1,訪問檔案時會寄存行。如果將buffering的值設為大於1的整數,表明了這就是的寄存區的緩衝大小。如果取負值,寄存區的緩衝大小則為系統預設。


3.2 當檔案被開啟後,得到的 file 對象有以下屬性
file.closed: 如果檔案已經被關閉,則返回true,否則返回false
file.mode:返回被開啟檔案的訪問模式
file.name:返迴文件的名稱
file.softspace:如果用print輸出後,必須跟一個空格符,則翻譯false,否則返回true

# -*- coding: UTF-8 -*-                                          fo = open ("a.txt",‘w‘)print "file name:",fo.nameprint "closed or not:",fo.closedprint "access mode:",fo.modeprint "末尾是否強制加空格",fo.softspacefo.close()print "closed or not?",fo.closedprint "file name:",fo.nameprint fo.mode

輸出

[email protected]:~/code$ python test.py file name: a.txtclosed or not: Falseaccess mode: w末尾是否強制加空格 0closed or not? Truefile name: a.txtw
4. write()方法,

可將任何字串寫入一個開啟的檔案夾,Python字串可以是位元據,不僅僅是文字,write()不會在字串的結尾添加分行符號

# -*- coding: UTF-8 -*-fo = open ("a.txt",‘w‘)fo.write("Hello world!!!!")                                      fo.close()
[email protected]:~/code$ python test.py [email protected]:~/code$ cat a.txt Hello [email protected]:~/code$ 
5. read()方法

從一個開啟的檔案中讀取字串,python字串可以是位元據,不僅僅是文字,文法:
fileobject.read([count])
在這裡,被傳遞的參數是要從已開啟檔案中讀取的位元組計數。該方法從檔案的開頭開始讀入,如果沒有傳入count,它會嘗試儘可能多地讀取更多的內容,很可能是直到檔案的末尾。

# -*- coding: UTF-8 -*-fo = open ("a.txt",‘r+‘)#fo.write("Hello World!!!") #同時使用的話會導致read()無法讀出str = fo.read()                                                  print strfo.close()

輸出:

[email protected]:~/code$ python test.py Hello world!!!
6. tell()方法

返迴文件內的當前位置,即,下一次讀寫會發生在檔案開頭多少位元組後
seek(offset[, from])方法改變當前檔案的位置,offset 表示要移動的位元組數,from 變數指定開始移動位元組的參考位置;如果 from 被設為0,則將檔案的開頭作為移動位元組的參考位置;如果設為1,則使用當前的位置作為參考位置;如果設為2,則將檔案的末尾作為參考位置

# -*- coding: UTF-8 -*-fo = open ("a.txt",‘r+‘)str = fo.read(5)print strposition = fo.tell()print "current position:",positionfo.seek(0,0)str = fo.read(5)                                                 print strfo.close()       

輸出:

[email protected]:~/code$ python test.py Hellocurrent position: 5Hello
7. File的其他相關方法

7.1 flush():重新整理緩衝區,即將緩衝區的資料立刻寫入檔案,同時清空緩衝區,而不是被動地等待緩衝區寫入
fileObject.flush()
進度條效果執行個體:

# -*- coding: UTF-8 -*-import sys,time                                                  for x in range(30):    sys.stdout.write(‘*‘)    sys.stdout.flush()    time.sleep(0.2)
  • 其輸出是每隔9.2秒輸出一個*,類似於進度條,**如果沒有flush()語句,將沒有進度條效果,而是在最後面一次性全部輸出來

7.2 next()方法在檔案使用迭代器時會使用到,該方法返迴文件的下一行,如果到達結尾(EOF),則出發StopIteration

# -*- coding: UTF-8 -*-                                          fo = open("a.txt","r+")for index in range(5):    line = fo.next()    print "第 %d 行 - %s"%(index, line)fo.close()

輸出:

[email protected]:~/code$ cat a.txt This is the first lineThis is the second lineThis is the third lineThis is the forth line[email protected]:~/code$ python test.py 第 0 行 - This is the first line第 1 行 - This is the second line第 2 行 - This is the third line第 3 行 - This is the forth lineTraceback (most recent call last):  File "test.py", line 4, in <module>    line = fo.next()StopIteration
  • 可以看到最後觸發了StopInteration,而且文本中每一行最後面有一個分行符號,print又會加一個分行符號,所以出現空行

7.3. readline()方法,從檔案讀取整行,包括‘\n‘字元;如果指定了一個非負的整數,則返回指定大小的位元組數,包括‘\n‘字元

# -*- coding: UTF-8 -*-fo = open("a.txt","r+")line = fo.readline()print lineline = fo.readline(5)print line        fo.close()       

輸出:

[email protected]:~/code$ python test.py This is the first lineThis

next()readline()對比

# -*- coding: UTF-8 -*-fo = open("a.txt","r+")for x in range(10):    line = fo.readline()    print linefo.close() 

輸出:

[email protected]:~/code$ python test.py This is the first lineThis is the second lineThis is the third lineThis is the forth line
  • 可以看到readline()讀到檔案末尾的時候還會繼續以空行往下讀,而不會報StopIteration錯誤。

7.4 readlines()方法讀取所有行(直到結束符EOF)並返回列表,該列表可以由Python的for ... in結構來進行處理,碰到結束符EOF則返回None

# -*- coding: UTF-8 -*-                                          fo = open(‘a.txt‘,‘r‘)print fo.readlines()fo.seek(0,0)for line in fo.readlines():    line = line.strip()    print lineprint fo.close()

輸出:

[email protected]:~/code$ python test.py [‘This is the first line\n‘, ‘This is the second line\n‘, ‘This is the third line\n‘, ‘This is the forth line\n‘]This is the first lineThis is the second lineThis is the third lineThis is the forth lineNone

7.5 truncate([size])用於截斷文字,如果指定了選擇性參數size,則表示截斷檔案為size個字元;如果沒有指定,則從當前位置起截斷,截斷之後size後面的所有字元被刪除

# -*- coding: UTF-8 -*-fo = open(‘a.txt‘,‘r+‘)                                          line = fo.readlines()print linefo.seek(0,0)fo.truncate()line = fo.readlines()print linefo.close()

輸出:

[email protected]:~/code$ python test.py [‘This is the first line\n‘, ‘This is the second line\n‘, ‘This is the third line\n‘, ‘This is the forth line\n‘][]

截取10個

# -*- coding: UTF-8 -*-                                          fo = open(‘a.txt‘,‘r+‘)line = fo.readlines()print linefo.seek(0,0)fo.truncate(10)line = fo.readlines()print linefo.close()

輸出:

[email protected]:~/code$ python test.py [‘This is the first line\n‘, ‘This is the second line\n‘, ‘This is the third line\n‘, ‘This is the forth line\n‘][‘This is th‘]

7.6 writelines([str])向檔案中寫入一序列的字串,這一序列字串可以是由迭代對象產生的,如一個字串列表。換行需要制定分行符號 \n。

# -*- coding: UTF-8 -*-                                          fo = open(‘a.txt‘,‘r+‘)seq = [‘Hello\n‘,‘World\n‘,‘Python\n‘]fo.writelines(seq)fo.close()

輸出:

[email protected]:~/code$ python test.py [email protected]:~/code$ cat a.txt HelloWorldPython

7.7 問題:在write()內容後,直接read檔案輸出會為空白?
這是因為指標已經在內容末尾,因此有2種解決方案:先close檔案,open後再讀取;第二是採用seek()讓指標先回到檔案頭
問題複現:

# -*- coding: UTF-8 -*-fo = open(‘a.txt‘,‘r+‘)seq = [‘Hello\n‘,‘World\n‘,‘Python\n‘]fo.writelines(seq)                                               print fo.read()fo.close()

輸出:

[email protected]:~/code$ python test.py 

解決:

# -*- coding: UTF-8 -*-fo = open(‘a.txt‘,‘r+‘)seq = [‘Hello\n‘,‘World\n‘,‘Python\n‘]fo.writelines(seq)   fo.seek(0,0) #讓指標回到檔案頭                                            print fo.read()fo.close()

輸出:

[email protected]:~/code$ python test.py HelloWorldPython
8. 重新命名和刪除檔案

Python的os模組提供了幫你執行檔案處理操作的方法,比如重新命名和刪除檔案
8.1 rename()用來重新命名,方法需要兩個參數,當前的檔案名稱和新檔案名稱。

os.rename(current_file_name, new_file_name)

8.2 remove()方法,刪除檔案,需要提供要刪除的檔案名稱作為參數
os.remove(file_name)

# -*- coding: UTF-8 -*-                                          import osos.rename("a.txt","b.txt")os.remove("b.txt")

8.3 mkdir()方法,在目前的目錄下建立新的目錄
8.4 chdir()方法,改變當前的目錄
8.4 getcwd()方法,顯示當前的工作目錄
8.4 rmdir()方法,刪除目錄,目錄名稱以參數傳遞,在刪除這個目錄之前,它的所有內容應該被清除

  1. 為了保證無論是否出錯都能正確地關閉檔案,我們可以使用 try ... finally 來實現
try:    f = open(‘/path/to/file‘, ‘r‘)    print f.read()finally:    if f:        f.close()

但是每次這麼寫太繁瑣,所以可加入with語句來自動調用close()f方法

with open(‘/path/to/file‘, ‘r‘) as f:    print f.read()

Python 檔案 I/O 2018-07-31

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.