文件 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。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。