Python3 寫入文件


Demo:

file = open("test.txt", "wb")
file.write("string")

上面這段代碼運行會報類型錯誤:TypeError: a bytes-like object is required, not 'str' 

wirte方法是將一個字節緩沖區寫入到目標文件中,而不支持string類型

write源碼:

def write(self, *args, **kwargs): # real signature unknown
"""
Write buffer b to file, return number of bytes written.

Only makes one system call, so not all of the data may be written.
The number of bytes actually written is returned. In non-blocking mode,
returns None if the write would block.
"""
pass

注:python3 將字符串寫入到目標文件時,必須先將字符串轉換為字節才能寫入,python2可以直接將字符串寫入到目標文件中


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM