python3檔案的讀寫操作

2021-10-09 22:09:11 字數 2345 閱讀 4148

open函式:對檔案進行讀寫操作前,先開啟檔案,獲取檔案的控制代碼:

注意

1:讀取檔案操作時read()方法讀取檔案所有內容,讀取出的結果為str型別

2:readlines()方法讀取檔案時,結果預設儲存為列表當中

r:唯讀模式

w:只寫模式【不可讀,不存在,則建立;存在,則清空重寫】

x:只寫模式【不可讀,不存在,則建立;存在,則報錯】

a:追加模式【不可讀,不存在,則建立;存在,則追加寫入】

「+」表示可同時讀寫檔案

r+:讀寫【不存在,不建立,從頂部開始寫,會覆蓋之前此位置的內容】

w+:讀寫【不存在,則建立;存在,則清空重寫】

x+:讀寫【不存在,則建立;存在,則報錯】

a+:讀寫【不存在,則建立;存在,則追加寫入】

注:不建議用r+的方式去寫入檔案,會使之前的檔案不完整。

使用 a+ 模式讀取檔案內容時,需要將指標切換到檔案左上角位置即seek(0)

read()方法
#讀取檔案.open方法乙個引數指讀取的檔名,預設開啟檔案為:唯讀模式r,只能讀取原檔案內容,不能寫內容

file

=open

("file2.txt"

)#可以使用tell方法獲取檔案指標

print

(file

.tell())

#使seek可以移動檔案指標

file

.seek(2)

print

(file

.tell())

#指定字元讀取2個字元

content =

file

.read(2)

print

(content)

#在使用open方法讀取txt的時候,操作完成後,要關閉檔案

file

.close(

)

write()方法
file

=open

('file3.txt'

,'a+'

)# 寫入一行

file

.seek(0)

file

.write(

"tomtom"

)#writelines寫入多行內容,可以是乙個字串,在需要換行的地方加上\n

file

.writelines(

"miss\nhello\npython"

)print

(file

.readline())

#寫入列表

name =

["augus\n"

,'tom'

]file

.writelines(name)

file

.close(

)

withopen函式
withopen 可以同時開啟多個檔案,缺省會關閉檔案

with

open

('file2.txt'

)as a,

open

('file3.txt'

,'a+'

)as b:

s= a.readlines(

)for i in s:

b.write(i)

缺省會關閉檔案,不要使用close方法

讀取csv檔案
逗號分隔值(comma-separated values,csv,有時也稱為字元分隔值,因為分隔字元也可以不是逗號)

import csv #匯入模組

#開啟檔案

file

=open

('test.csv'

)#讀取開啟的csv檔案,讀取了所有內容

info = csv.reader(

file

)#輸出後列表中的每一行是乙個列表

for row in info:

print

(row)

print

("***********"

)

對csv檔案進行write操作

import csv

#以a+模式開啟檔案

file

=open

("test.csv"

,'a+'

)a = csv.writer(

file

)#寫入一行內容

list1 =

['hello'

,'yes'

,'augus'

]a.writerows(

"tom"

)

Python3 檔案讀寫

python open 方法用於開啟乙個檔案,並返回檔案物件,在對檔案進行處理過程都需要使用到這個函式 1.讀取檔案 with open test json dumps.txt mode r encoding utf 8 as f seek 移動游標至指定位置 f.seek 0 read 讀取整個檔...

python3 檔案讀寫1

檔案 開啟檔案 r 檔案可讀可寫,不會建立檔案,從頂部開始寫,會覆蓋之前此位置的內容 with open output.txt r as f1 print name of the file f1.name 向開啟的檔案寫入內容,並沒有從檔案頂部開始寫啊,是為什麼?f1.write begin 追加在...

Python3 檔案讀寫模式

1 r 開啟唯讀檔案,該檔案必須存在。2 r 開啟可讀寫的檔案,該檔案必須存在。3 w 開啟只寫檔案,若檔案存在則檔案長度清為0,即該檔案內容會消失。若檔案不存在則建立該檔案。4 w 開啟可讀寫檔案,若檔案存在則檔案長度清為零,即該檔案內容會消失。若檔案不存在則建立該檔案。5 a 以附加的方式開啟只...