python文本文件操作方法
时间: 2023-11-23 21:57:09 浏览: 38
以下是Python文本文件操作的几种方法:
1. 使用open()函数打开文件,读取文件内容并关闭文件:
```python
file = open("文件路径", mode="r", encoding="utf-8")
content = file.read()
file.close()
print(content)
```
2. 使用with语句打开文件,读取文件内容并自动关闭文件:
```python
with open("文件路径", mode="r", encoding="utf-8") as file:
content = file.read()
print(content)
```
3. 使用open()函数打开文件,写入文件内容并关闭文件:
```python
file = open("文件路径", mode="w", encoding="utf-8")
file.write("写入的内容")
file.close()
```
4. 使用with语句打开文件,写入文件内容并自动关闭文件:
```python
with open("文件路径", mode="w", encoding="utf-8") as file:
file.write("写入的内容")
```
5. 使用open()函数打开文件,追加文件内容并关闭文件:
```python
file = open("文件路径", mode="a", encoding="utf-8")
file.write("追加的内容")
file.close()
```
6. 使用with语句打开文件,追加文件内容并自动关闭文件:
```python
with open("文件路径", mode="a", encoding="utf-8") as file:
file.write("追加的内容")
```
7. 使用open()函数打开文件,读取并写入文件内容并关闭文件:
```python
file = open("文件路径", mode="r+", encoding="utf-8")
content = file.read()
file.write("写入的内容")
file.close()
print(content)
```
8. 使用open()函数打开文件,清空文件内容并关闭文件:
```python
file = open("文件路径", mode="w", encoding="utf-8")
file.truncate()
file.close()
```