Python 中的文件操作是通过内置的 open()
函数来实现的。您可以使用 open()
函数打开一个文件,并进行读取、写入或追加等操作。以下是一些常见的文件操作示例:
- 读取文件内容:
with open('example.txt', 'r') as file:
content = file.read()
print(content)
- 写入内容到文件:
with open('example.txt', 'w') as file:
file.write('Hello, World!')
- 追加内容到文件:
with open('example.txt', 'a') as file:
file.write('\nAppending new content')
在这些示例中,with open()
语句用于打开文件,并在代码块结束时自动关闭文件。您可以根据需要选择不同的模式('r' - 读取,'w' - 写入,'a' - 追加)来打开文件。