python 寫入檔案形式

2022-05-15 19:55:00 字數 960 閱讀 5693

寫入檔案的不只是文字,還有二進位制等,位元組流是什麼樣式關係到能否寫入檔案。

以獲取網頁寫入檔案操作示例:

response = requests.get("

")print

(response.encoding)

print(response.text) #

文字格式

print(response.content) #

位元組格式

with open (

'bai.html

' ,'

w',encoding='

utf-8

') as f:

f.write(response.text)

#如果沒有 encoding='utf-8' ,在windows預設gbk開啟檔案,寫入就會有問題

#如果網頁的編碼比如是 iso-8859-1 ,那麼 encoding='iso-8859-1' 也是可以成功寫入

with open (

'bai2.html

' ,'wb'

) as f:

f.write(response.content)

在這裡注意有 編碼格式,在window下預設是gbk,網頁或者linux下是 unicode編碼。

w:以寫方式開啟,

a:以追加模式開啟 (從 eof 開始, 必要時建立新檔案)

r+:以讀寫模式開啟

w+:以讀寫模式開啟 (參見 w )

a+:以讀寫模式開啟 (參見 a )

rb:以二進位制讀模式開啟

wb:以二進位制寫模式開啟 (參見 w )

ab:以二進位制追加模式開啟 (參見 a )

rb+:以二進位制讀寫模式開啟 (參見 r+ )

wb+:以二進位制讀寫模式開啟 (參見 w+ )

ab+:以二進位制讀寫模式開啟 (參見 a+ )fp.read([size])  

CStdioFile 以字串形式寫入檔案一行

cstdiofilemfile cfileexception mexcept mfile.open t d test.ini cfile modecreate cfile modenotruncate cfile modewrite,mexcept mfile.seektoend cstring s...

python檔案的寫入

wirte 方法把字串寫入檔案,writelines 方法可以把列表中儲存的內容寫入檔案。f file hello.txt w li hello world n hello china n f.writelines li f.close 檔案的內容 hello world hello china w...

Python 寫入XML 檔案

需要將test case轉為xml檔案方式用於讀取。中test suit.txt 是用來儲存原來的case檔案的,故做了一點string的處理,用split 函式摳出自己需要的字段 import xml.dom.minidom impl xml.dom.minidom.getdomimplement...