当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


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。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。