用python将txt文件转化为csv
时间: 2023-10-23 08:08:45 浏览: 213
可以使用Python中的csv模块来将txt文件转换为csv文件,具体步骤如下:
1. 打开txt文件并读取数据
```
with open('data.txt', 'r') as f:
data = f.readlines()
```
2. 对数据进行处理,将其转换为二维列表形式
```
data = [line.strip().split() for line in data]
```
3. 打开csv文件并将数据写入
```
import csv
with open('data.csv', 'w', newline='') as f:
writer = csv.writer(f)
writer.writerows(data)
```
完整代码如下:
```
import csv
with open('data.txt', 'r') as f:
data = f.readlines()
data = [line.strip().split() for line in data]
with open('data.csv', 'w', newline='') as f:
writer = csv.writer(f)
writer.writerows(data)
```
阅读全文