python 文件操作
时间: 2023-10-14 22:28:19 浏览: 13
好的,下面是 Python 中文件操作的一些基本操作。
- 读文件
使用 `open()` 函数打开文件,返回一个文件对象,然后使用 `.read()` 方法读取文件内容:
```
f = open("filename.txt", "r")
content = f.read()
f.close()
```
- 写文件
使用 `open()` 函数打开文件,如果文件不存在,会自动创建一个新文件。使用 `.write()` 方法写入内容:
```
f = open("filename.txt", "w")
f.write("Some text")
f.close()
```
- 追加内容
使用 `open()` 函数打开文件,使用 `"a"` 模式打开文件,然后使用 `.write()` 方法写入内容:
```
f = open("filename.txt", "a")
f.write("Some more text")
f.close()
```
- 使用 `with` 语句
使用 `with` 语句可以省去手动关闭文件的步骤,代码也更加简洁:
```
with open("filename.txt", "r") as f:
content = f.read()
```
- 读取文件中的一行
使用 `.readline()` 方法可以读取文件中的一行内容:
```
with open("filename.txt", "r") as f:
line = f.readline()
```
还有很多其他的文件操作,比如读取文件中的所有行、迭代文件对象、处理 CSV 文件等。你可以参考 Python 官方文档或者搜索相关资料来了解更多。