python处理txt文件
时间: 2023-10-12 20:05:10 浏览: 87
Python可以非常方便地处理txt文件,以下是一些基本的操作:
1. 读取txt文件
使用open()函数打开txt文件,然后使用read()方法读取文件内容。例如:
```python
with open('example.txt', 'r') as f:
content = f.read()
```
2. 写入txt文件
使用open()函数打开txt文件,然后使用write()方法写入内容。例如:
```python
with open('example.txt', 'w') as f:
f.write('Hello, world!')
```
如果要在文件末尾追加内容,需要使用追加模式'a':
```python
with open('example.txt', 'a') as f:
f.write('Hello, world again!')
```
3. 逐行读取txt文件
使用for循环逐行读取txt文件内容。例如:
```python
with open('example.txt', 'r') as f:
for line in f:
print(line)
```
4. 批量处理多个txt文件
使用os模块遍历文件夹,然后使用open()函数读写每个txt文件。例如:
```python
import os
folder_path = 'folder_path'
for filename in os.listdir(folder_path):
if filename.endswith('.txt'):
with open(os.path.join(folder_path, filename), 'r') as f:
content = f.read()
# do something with content
```
阅读全文
相关推荐


















