當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


Python File write()用法及代碼示例


文件 write() 方法

write() 方法是 Python 內置的方法,用於寫入文件中的內容。

用法:

    file_object.write(text/bytes)

參數:

  • text/bytes– 指定要寫入文件的文本。

返回值:

這個方法的返回類型是<class 'int'>,它返回文件中寫入的總數。

例:

# Python File write() Method with Example

# creating a file 
myfile = open("hello.txt", "w")

# writing to the file
res = myfile.write("Hello friends, how are you?")
print(res, "bytes written to the file.")
# closing the file
myfile.close()

# reading content from the file
myfile = open("hello.txt", "r")
print("file content is...")
print(myfile.read())
myfile.close();

# writing more content to the file
# opening file in append mode
myfile = open("hello.txt", "a")

# writing to the file
res = myfile.write("Hey, I am good!")
print(res, "bytes written to the file.")
# closing the file
myfile.close()

# reading content from the file again
myfile = open("hello.txt", "r")
print("file content is...")
print(myfile.read())
myfile.close()

輸出

27 bytes written to the file.
file content is...
Hello friends, how are you?
15 bytes written to the file.file content is...
Hello friends, how are you?Hey, I am good!


相關用法


注:本文由純淨天空篩選整理自 Python File write() Method with Example。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。