文件 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 writelines()用法及代码示例
- Python File writable()用法及代码示例
- Python File tell()用法及代码示例
- Python File seek()用法及代码示例
- Python File flush()用法及代码示例
- Python File read()用法及代码示例
- Python File truncate()用法及代码示例
- Python File fileno()用法及代码示例
- Python File open()用法及代码示例
- Python File isatty()用法及代码示例
- Python File readable()用法及代码示例
- Python File readlines()用法及代码示例
- Python File close()用法及代码示例
- Python File readline()用法及代码示例
- Python File seekable()用法及代码示例
- Python numpy.less()用法及代码示例
- Python Sympy Permutation.list()用法及代码示例
- Python Matplotlib.figure.Figure.subplots_adjust()用法及代码示例
- Python numpy.tril()用法及代码示例
- Python Matplotlib.pyplot.matshow()用法及代码示例
注:本文由纯净天空筛选整理自 Python File write() Method with Example。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。