1. 程式人生 > >Python小練習1:.txt檔案常用讀寫操作

Python小練習1:.txt檔案常用讀寫操作

.txt檔案常用讀寫操作

     本文通過一個例項來介紹讀寫txt檔案的各種常用操作,問題修改自coursera上南京大學的課程:用Python玩轉資料。

     直接進入正題,考慮下面為練習讀寫txt檔案的各種操作而設計的一個具體問題

     問題如下:

     (1) 在任意位置建立一個.py檔案,如'D:/程式設計練習/python練習/Week2_02.py'

     (2) 在D盤下建立一個檔案Blowing in the wind.txt,即‘D:\Blowing in the wind.txt’

     其內容是:

How many roads must a man walk down

Before they call him a man

How many seas must a white dove sail

Before she sleeps in the sand

How many times must the cannon balls fly

Before they're forever banned

The answer my friend is blowing in the wind

The answer is blowing in the wind

     (3) 在檔案頭部插入歌名“Blowin’ in the wind”

     (4) 在歌名後插入歌手名“Bob Dylan”

     (5) 在檔案末尾加上字串“1962 by Warner Bros. Inc.”

     (6) 在螢幕上列印檔案內容,最好加上自己的設計

     (7) 以上每一個要求均作為一個獨立的步驟進行,即每次都重新開啟並操作檔案

--------------------------------------------------------------------------------------------------------------------

     程式程式碼如下:

import os
#Python的os模組提供了執行檔案和目錄處理操作的函式,例如重新命名和刪除檔案。
os.chdir('D:\\') #更改目錄 

#-------------------------------------------------------------------------
#建立一個檔案,將歌詞寫入
f1=open(r'Blowing in the wind.txt','w')
f1.write('How many roads must a man walk down \n')
f1.write('Before they call him a man \n')
f1.write('How many seas must a white dove sail \n')
f1.write('Before she sleeps in the sand \n')
f1.write('How many times must the cannon balls fly \n')
f1.write('Before they\'re forever banned \n')
f1.write('The answer my friend is blowing in the wind \n')
f1.write('The answer is blowing in the wind\n')
f1.close()#檔案使用後記得關閉

#--------------------------------------------------------------------------
#在檔案頭部插入歌曲名
f2=open(r'Blowing in the wind.txt','r+')#mode引數不能用'w+',這會清空原內容
lyrics =f2.readlines()
lyrics.insert(0,'Blowin\'in the wind\n')#在第一行新增歌曲名
f2.seek(0,0)#將檔案指標移動到檔案開頭處
f2.writelines(lyrics)
f2.close()

#這是一種錯誤的寫法,將歌詞的第一行抹去了一部分
#f2=open(r'Blowing in the wind.txt','r+')
#f2.seek(0,0)#將檔案指標移動到檔案開頭處
#f2.write('Blowin’ in the wind\n')
#f2.close()

#--------------------------------------------------------------------------
#在歌名後插入歌手名(實現同上一步)
f3=open(r'Blowing in the wind.txt','r+')#mode引數不能用'w+',這會清空原內容
lyrics =f3.readlines()
lyrics.insert(1,'——Bob Dylan\n')#在第一行新增歌手名
f3.seek(0,0)#將檔案指標移動到檔案開頭處
f3.writelines(lyrics)
f3.close()

#--------------------------------------------------------------------------
#在檔案末尾加上字串“1962 by Warner Bros. Inc.” 
f4=open(r'Blowing in the wind.txt','a')#mode引數選擇'a',代表追加模式.
f4.write('1962 by Warner Bros. Inc.')#追加模式下,可以直接向檔案末尾write內容
f4.close()

#--------------------------------------------------------------------------
#在螢幕上列印檔案內容(最好加一些自己的格式設計)
f5=open(r'Blowing in the wind.txt','r')
article =f5.readlines()#讀取檔案內容
#按照自己的方式顯示
for i in range(0,len(article)):
    if 1<i<len(article)-1:
        print('\t'+article[i])
    else:
        print('\t\t'+article[i])
f5.close()

     執行後.txt檔案中的內容為:

     螢幕上的輸出為: