python基礎(十二) 檔案的操作

2022-01-09 23:09:01 字數 3357 閱讀 8853

前言:本文主要介紹python中檔案的操作,包括開啟檔案、讀取檔案、寫入檔案、關閉檔案以及上下文管理器。

python中open() 方法用於開啟乙個檔案,並返回檔案物件,在對檔案進行處理過程都需要使用到這個函式,如果該檔案無法被開啟,會丟擲乙個oserror。

使用語法:open(引數1,引數2,引數3)

引數1:檔名

引數2:開啟的模式

引數3:編碼方式(encoding = "utf-8")

file = '

test.txt'#

檔案與當前py檔案在同乙個目錄下

#file2 = r'

d:\myworkspace\test\test.txt

'file = open(file, '

r', encoding='

utf-8

') #

以讀取方式開啟檔案

print(file.read()) #

讀取檔案的內容

file.close()  #

開啟檔案使用完後記得關閉檔案

執行結果:

c:\software\python\python.exe d:/myworkspace/test/test.py

這是乙個測試用的txt文字

process finished with exit code 0

關閉檔案:close()方法,在上面開啟檔案例子中已經舉例。

注意:使用 open() 方法一定要保證關閉檔案物件,即呼叫 close() 方法,關閉檔案

file = open('

test.txt

', '

w', encoding='

utf-8

') #

以寫入方式開啟檔案

file.write('

今天是星期四')

file.close()

執行後檢視text.txt檔案

以寫入方式開啟檔案

#向檔案寫入乙個序列字串列表,如果需要換行則要自己加入每行的換行符,注意最後一行不需要加換行符,不然檔案最後會有一行空白行

file.writelines(['

今天是星期四\n

', '

明天是星期五\n

', '

後天是星期六'])

file.close()

執行後檢視text.txt檔案

1.讀取全部內容  

read()

file = open('

test.txt

', '

r', encoding='

utf-8

') #

以寫入方式開啟檔案

res1 =file.read()

print(res1)

file.close()

執行結果:

c:\software\python\python.exe d:/myworkspace/test/test.py

今天是星期四

明天是星期五

後天是星期六

process finished with exit code 0

2.讀取一行  

file.readline()

file = open('

test.txt

', '

r', encoding='

utf-8

') #

以寫入方式開啟檔案

res2 =file.readline()

print(res2)

file.close()

執行結果:

c:\software\python\python.exe d:/myworkspace/test/test.py

今天是星期四

process finished with exit code 0

3.按行讀取所有內容

file.readlines()

file = open('

test.txt

', '

r', encoding='

utf-8

') #

以寫入方式開啟檔案

res3 = file.readlines() #

一行儲存為乙個元素,組成乙個列表,每行(除了最後一行)後面會帶有乙個換行符

print

(res3)

file.close()

執行結果:

c:\software\python\python.exe d:/myworkspace/test/test.py['

今天是星期四\n

', '

明天是星期五\n

', '

後天是星期六']

process finished with exit code 0

file = open('

test.txt

', '

r', encoding='

utf-8')

print(file.tell()) #

返回此時游標的位置(檢視指標)

file.seek(0)) #

將檔案游標移動到起始位置

file.seek(70)) #

將檔案游標移動到70的位置

開啟open返回檔案控制代碼物件的上下文管理器(執行完with裡的**語句之後,會自動關閉檔案)

with open(file="

text.txt

", mode="

r", encoding="

utf-8

") as f:

c =f.read()

print(c)

Python學習筆記(十二) 檔案操作

本節主要介紹檔案相關的操作 寫乙個檔案 writefile chen.txt hello python chen mo how are youwriting chen.txttxt open chen.txt 讀取全部內容 allcontent txt.read print allcontent h...

Python 基礎 檔案的操作

1.預設方法 需手動關閉 開啟後要自己關閉 heine open heine.txt poem heine.read print poem print heine.closed 獲取是否關閉 heine.close 只能手動進行關閉 print heine.closed 2.open使用後自動關閉 ...

Python基礎 檔案操作

使用 open 能夠開啟乙個檔案,open 的第乙個引數為檔名和路徑 my file.txt 第二個引數為將要以什麼方式開啟它,比如w為可寫方式.如果計算機沒有找到 my file.txt 這個檔案,w 方式能夠建立乙個新的檔案,並命名為 my file.txt 例項 text tthis is m...