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 示例