python檔案操作

2021-09-25 15:11:08 字數 3018 閱讀 7198

普通程式讀寫檔案的時候需要向作業系統發出請求,請求作業系統開啟乙個檔案物件,通過這個檔案物件來進行讀寫

with

open

(str1,

"r",encoding=

"utf-8"

)as f:

pass

f =open(path,mode,encoding,errors)

path:檔案路徑

mode:模式 r:讀取,預設

encoding:編碼格式

errors預設strict[嚴格的] ignore 忽略編碼錯誤

f:開啟的檔案物件,f是乙個迭代f器

f.read()

一次性讀取所有內容

f.read(size)

一次性讀取size位元組

f.readlines()

一次性讀取所有行

f.readline()

一次性讀取一行

f.close()

關閉檔案

當使用檔案讀寫時,需要在結尾使用f.close語句,不然會出現錯誤

語法:with open(path,mode,encoding) as 檔名:

對檔案進行操作

當檔案一旦關閉,不能對此檔案進行操作。

open(path,mode) as f:

f.read()

mode: rb 讀取二進位制檔案

結論:普通檔案可以使用r/rb來進行讀取,但是二進位制的檔案

只能使用rb的方式來進行讀取。

open(path,mode,encoding)

path:路徑

mode:w/a

encoding:寫入編碼格式

f.write(str1)

寫入的必須是字串

使用w的方式寫入:當path存在的時候,則覆蓋,若path不存在

則建立。

使用a的方式寫入的時候,若path存在,則追加,若path不存在,

則建立

f.writelines([「hello」,「good」,「nice」])

將列表中的字串一次性寫入到檔案中

stingio

from io import stringio

from io import bytesio

bio = bytesio(

)# 要求寫入的必須是二進位制的

bio.write(

"中國"

.encode())

# 檢視bio內容

print

(bio.getvalue(

).decode(

))

#-- author:zhangjiao --

import csv

『』』需求:封裝一下csv檔案的讀取,要求讀取前n行,並且讀取的資料以列表的方式返回。

def

readcsv

(path,n)

:with

open

(path,

"r",encoding=

"gbk"

,errors=

"ignore"

)as f:

csv_reader = csv.reader(f)

datalist =

for x in

range

(n):

try:

next

(csv_reader)

)except stopiteration as e:

break

return datalist

defreadandwrite

(path1,path2,n)

:with

open

(path1,

"r",encoding=

"gbk"

)as f:

with

open

(path2,

"w",encoding=

"gbk"

)as f2:

csv_reader = csv.reader(f)

csv_writer = csv.writer(f2)

for x in

range

(n):

csv_writer.writerow(

next

(csv_reader)

)if __name__ ==

'__main__'

: res = readcsv(

"002.csv",5

)print

(res)

with

open

("002.csv"

,"r"

,encoding=

"gbk"

)as f:

csv_reader = csv.reader(f)

print

(next

(csv_reader)

)with

open

("0002.csv"

,"w"

,encoding=

"gbk"

)as f2:

csv_writer = csv.writer(f2)

for row in res:

csv_writer.writerow(row)

readandwrite(

"002.csv"

,"1.csv",50

)

python 檔案操作

簡明 python 教程 中的例子,python 執行出錯,用open代替file 可以執行。poem programming is fun when the work is done if you wanna make your work also fun use python f open e ...

python檔案操作

1,將乙個路徑名分解為目錄名和檔名兩部分 a,b os.path.split c 123 456 test.txt print a print b 顯示 c 123 456 test.txt 2,分解檔名的副檔名 a,b os.path.splitext c 123 456 test.txt pri...

Python 檔案操作

1.開啟檔案 如下 f open d test.txt w 說明 第乙個引數是檔名稱,包括路徑 第二個引數是開啟的模式mode r 唯讀 預設。如果檔案不存在,則丟擲錯誤 w 只寫 如果檔案 不存在,則自動建立檔案 a 附加到檔案末尾 r 讀寫 如果需要以二進位制方式開啟檔案,需要在mode後面加上...