python 檔案讀寫5個執行個體__python

來源:互聯網
上載者:User

在部落格(python本機資料擷取   網址:http://blog.csdn.net/sxingming/article/details/51333663)中,我們詳細介紹了python中檔案讀寫的各種方法。

本文通過5個具體例子,樣本一下檔案的讀寫操作。

1》將檔案companies.txt中的字串前加上序號1,2,3……後,寫到另一個檔案scompanies.txt中。
檔案companies.txt中的內容如下圖:


>>> f1=open(r'C:\Users\Administrator\Desktop\companies.txt','r')

>>> companyNames=f1.readlines()
>>> for i in range(0,len(companyNames)):
...     companyNames[i]=str(i+1)+' '+companyNames[i]
... 
>>> f1.close()
>>> f2=open(r'C:\Users\Administrator\Desktop\scompanies.txt','w')
>>> f2.writelines(companyNames)
>>> f2.close()
運行程式後,檔案scompanies.txt中的內容如下圖:


2》開啟檔案companies.txt,在尾部追加一行'alibaba',然後讀出檔案內容。
>>> f1=open(r'C:\Users\Administrator\Desktop\companies.txt','a+')
>>> f1.write('\n')
>>> f1.write('alibaba')
>>> f1.seek(0,0)
>>> l=f1.readlines()
>>> f1.close()
>>> l
['Apple Inc.\n', 'Google Inc.\n', 'Facebook,Inc.\n', 'Microsoft Corporation\n', 'alibaba']

3》開啟檔案companies.txt,在第二行後,添加一獨立的新行'love python'。
>>> f=open(r"C:\Users\Administrator\Desktop\companies.txt",'r+')#注意開啟模式
>>> n=2
>>> l=f.readlines()
>>> l
['Apple Inc.\n', 'Google Inc.\n', 'Facebook,Inc.\n', 'Microsoft Corporation\n', 'alibaba']
>>> l.insert(n,'love python\n')#字串末尾記得寫分行符號
>>> l
['Apple Inc.\n', 'Google Inc.\n', 'love python\n', 'Facebook,Inc.\n', 'Microsoft Corporation\n', 'alibaba']
>>> f.seek(0)#將檔案指標移到檔案開頭
>>> f.writelines(l)
>>> f.close()

插入新行後,檔案內容如下:


4》讀取整個檔案的內容
可以直接使用readlines()函數,如下:
>>> f=open(r"C:\Users\Administrator\Desktop\companies.txt",'r')
>>> l=f.readlines()
>>> f.close()
>>> print l
['Apple Inc.\n', 'Google Inc.\n', 'love python\n', 'Facebook,Inc.\n', 'Microsoft Corporation\n', 'alibaba']

5》讀取整個檔案內容,不使用readlines()函數,如下:
>>> f=open(r"C:\Users\Administrator\Desktop\companies.txt",'r')
>>> lines=[]
>>> for line in f: #檔案是一個可迭代對象
...     lines.append(line)
... 
>>> f.close()
>>> print lines
['Apple Inc.\n', 'Google Inc.\n', 'love python\n', 'Facebook,Inc.\n', 'Microsoft Corporation\n', 'alibaba']


(完)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.