AdSense

網頁

2019/11/16

Python 讀取文字檔案 read text files

Python讀取文字檔並印出內容範例如下。


Python可直接使用內建的open()函式來讀取或寫出檔案。

例如下面是要被讀取的文字檔lyrics.txt的內容,lyrics.txt放在D:\路徑下。

lyrics.txt

Boy Pablo - T-Shirt

Sweaty body, the sun is burning
Yeah, I'm feelin' kinda hot right now
And my t-shirt is now useless

I thought I was ready
Obviously I wasn't
My body's burnin' and I got to get inside
'Cause I'm feelin' kinda dizzy

But remember that I love you
And you know I always will
And remember that I'll dream about you baby
(I'll dream about you baby)

Baby I have to go, really need to leave now
Yeah I'm putting on my t-shirt
It's not what I want to but I have to get inside
'Cause I'm feelin' way too dizzy

But remember that I love you
And you know I always will
And remember that I'll dream about you baby
(I'll dream about you baby)

But remember that I love you
And you know I always will

Python讀取lyrics.txt的程式如下。

open()函式第一個參數為檔案路徑,第二個參數為執行模式(mode),'r'代表讀取模式,回傳file object

要注意的第一個檔案路徑參數如果使用相對路徑,則相對路徑的位置是Python執行時的路徑,而不是被執行的py檔路徑。

f = open('d:/lyrics.txt', 'r') # 開啟並讀取檔案
lines = f.readlines() # 讀取檔案內容的每一行文字為陣列

for line in lines:
    print(line, end = '') # 印出時結尾不印new line

f.close() # 關閉檔案

或是用with來讀取並印出檔案內容。with結束時會自動關閉檔案,也就是不用另外寫f.close()

with open('d:/lyrics.txt', 'r') as f:
    content = f.read() # 讀取檔案內容
    print(content, end = '') # 印出時結尾不印new line

印出的結果:

Boy Pablo - T-Shirt

Sweaty body, the sun is burning
Yeah, I'm feelin' kinda hot right now
And my t-shirt is now useless

I thought I was ready
Obviously I wasn't
My body's burnin' and I got to get inside
'Cause I'm feelin' kinda dizzy

But remember that I love you
And you know I always will
And remember that I'll dream about you baby
(I'll dream about you baby)

Baby I have to go, really need to leave now
Yeah I'm putting on my t-shirt
It's not what I want to but I have to get inside
'Cause I'm feelin' way too dizzy

But remember that I love you
And you know I always will
And remember that I'll dream about you baby
(I'll dream about you baby)

But remember that I love you
And you know I always will
And remember that I'll dream about you baby

參考:

沒有留言:

AdSense