如何使用Python读取和写入文件?
在Python中,读取和写入文件可以通过内置的`open()`函数实现。以下是常见的操作方式:
1. **读取文件**
假如有一个名为`example.txt`的文件,可通过以下方式读取其内容:
```python
# 打开文件并读取所有内容
with open("example.txt", "r", encoding="utf-8") as file: # "r" 模式表示读取
content = file.read()
print(content)
```
2. **写入文件**
要向文件中写入内容,可以使用`w`模式(会覆盖旧内容)或`a`模式(追加新内容):
```python
# 写入文件(会覆盖原有内容)
with open("example.txt", "w", encoding="utf-8") as file: # "w" 模式表示写入
file.write("这是新的内容。
")
# 追加内容到文件
with open("example.txt", "a", encoding="utf-8") as file: # "a" 模式表示追加
file.write("这是追加的内容。
")
```
3. **逐行读取文件**
如果文件内容较大,可以逐行读取以节省内存:
```python
with open("example.txt", "r", encoding="utf-8") as file:
for line in file:
print(line.strip()) # 用strip()去掉每行末尾的换行符
```
4. **检查文件是否存在**
为了避免文件不存在时报错,可以使用`os`模块中的`os.path.exists()`方法:
```python
import os
if os.path.exists("example.txt"):
with open("example.txt", "r", encoding="utf-8") as file:
print(file.read())
else:
print("文件不存在!")
```
注意事项:
- 文件操作完成后可以用`with open()`的方式自动关闭文件,这是一种更安全的文件操作方式。
- 创建文件时,如果指定的文件不存在且模式是`w`或`a`,则会自动创建新文件。
- 读取和写入时务必注意编码问题,如处理中文字符时建议指定`encoding="utf-8"`。
若文章对您有帮助,帮忙点个赞!
(微信扫码即可登录,无需注册)