Python is a powerful programming language that provides a variety of file reading and writing modes to meet different needs. This article will introduce the commonly used file reading and writing modes in Python and give corresponding code examples.
Sample code:
# 打开文件 file = open('example.txt', 'r') # 读取文件内容 content = file.read() # 关闭文件 file.close() # 打印文件内容 print(content)
Sample code:
# 打开文件 file = open('example.txt', 'w') # 写入内容 file.write('Hello, World!') # 关闭文件 file.close()
Sample code:
# 打开文件 file = open('example.txt', 'a') # 追加内容 file.write('Hello, World!') # 关闭文件 file.close()
Sample code:
# 打开文件 file = open('example.txt', 'r+') # 读取文件内容 content = file.read() print(content) # 在文件开头写入新内容 file.seek(0) file.write('Hello, Python!') # 关闭文件 file.close()
Sample code:
# 打开二进制文件 file = open('example.jpg', 'rb') # 读取文件内容 content = file.read() # 关闭文件 file.close()
The above is the commonly used file reading and writing mode in Python. Select the appropriate mode according to specific needs to operate files efficiently.
The above is the detailed content of What are the options for file reading and writing modes in Python?. For more information, please follow other related articles on the PHP Chinese website!