python 示例
文件write()方法 (File write() Method)
write() method is an inbuilt method in Python, it is used to write the content in the file.
write()方法是Python中的內置方法,用于將內容寫入文件中。
Syntax:
句法:
file_object.write(text/bytes)
Parameter(s):
參數:
text/bytes – Specifies the text to be written in the file.
文本/字節 –指定要寫入文件的文本。
Return value:
返回值:
The return type of this method is <class 'int'>, it returns the total number of the written in the file.
此方法的返回類型為<class'int'> ,它返回文件中寫入的總數。
Example:
例:
# 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()
Output
輸出量
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!
翻譯自: https://www.includehelp.com/python/file-write-method-with-example.aspx
python 示例