1. 程式人生 > >Python學習筆記文件操作

Python學習筆記文件操作

color 學習 技術 寫入 自己 adl txt文件 格式 class

隨筆記錄方便自己和同路人查閱。

#------------------------------------------------我是可恥的分割線-------------------------------------------

文件操作有創建、寫入、關閉

創建時可指定模式‘r‘為讀模式、‘w’為寫模式(此模式多次寫入會覆蓋以後內容)、‘a’模式為可讀可寫模式

#------------------------------------------------我是可恥的分割線-------------------------------------------

1、創建文件

(1)無路徑創建文件(源碼所在路徑C:\Users\Administrator\PycharmProjects\test\day3)

song = open(‘text_day1.txt‘,‘w‘,encoding=‘utf-8‘)

  open()函數,如果文件存在打開此文件,如果文件不存在創建文件並打開,‘text_day1.txt‘為打開的文件名,‘w‘為打開方式,encoding=‘utf-8‘為指定編碼格式

  運行結果:

  會在默認路徑下創建一個text_day1.txt文件(C:\Users\Administrator\PycharmProjects\test\day3會自動創建)

(2)在指定路徑下創建文件

song = open(‘E:\\Python_temporary\\text_day1.txt‘,‘w‘,encoding=‘utf-8‘)

  運行結果:

  會在E:\\Python_temporary創建text_day1.txt文件

2、文件寫入

(1)‘w’模式寫入

song = open(‘E:\\Python_temporary\\text_day1.txt‘,‘w‘,encoding=‘utf-8‘)
song.write(‘hello‘)

  運行結果:在E:\\Python_temporary\\text_day1.txt文件中寫入了hello內容

  使用此種方式寫入,文件原內容會被覆蓋(慎用),不信你可以試一下

技術分享圖片

(2)‘a’模式寫入

song = open(‘E:\\Python_temporary\\text_day1.txt‘,‘a‘,encoding=‘utf-8‘)
song.write(‘hello  1\n‘)
song.write(‘hello  2\n‘)

  運行結果:此種方式為追加模式,寫入內容會被追加到後面(但不會自動換行) \n幫助換行

技術分享圖片

3、文件讀取

(1)read()函數讀取

song = open(‘E:\\Python_temporary\\text_day1.txt‘,‘r‘,encoding=‘utf-8‘).read()
print(song)

  運行結果:輸出了hello,是因為我文件中內容就是hello

技術分享圖片

(2)只讀前五行(使用五環之歌歌詞作為讀取內容)

song = open(‘E:\\Python_temporary\\五環之歌.txt‘,‘r‘)
for i in range(5):
    print(song.readline(),end=‘‘)

  運行結果:

技術分享圖片

(3)readlines()函數,此函數會把讀取的內容存為列表

song = open(‘E:\\Python_temporary\\五環之歌.txt‘,‘r‘)
for line in song.readlines():#readlines()讀取文件後把每一行作為一個元素存為列表
    print(line.strip())#strip()函數去除所有的空格和換行

  運行結果:

技術分享圖片

(4)指定某一行打印自己想要的

song = open(‘E:\\Python_temporary\\五環之歌.txt‘,‘r‘)#讀取文件
count = 0#計數
for line in song:#循環
    count +=1#計數加一
    if count == 9:#如果計數等於9打印下面內容並continue跳過
        print(‘----------我是分割線--------‘)
        continue
    print(line)

  

(5)closs()函數關閉

4、文件的其他用法

()

Python學習筆記文件操作