帮我写一个python代码,将某一文件夹内的txt文件转为csv文件,要求让txt内每一行数据按照空格区分,并分别输入到csv文件的不同单元格中,避免“生成的csv文件,每一行的数据都挤在了一个单元格中”这种情况
时间: 2024-03-06 19:50:25 浏览: 148
好的,可以试试以下代码:
```python
import os
import csv
# 指定要将 txt 文件转为 csv 的文件夹路径
txt_folder = '/path/to/txt/folder'
# 指定 csv 文件保存路径
csv_file = '/path/to/output/csv/file.csv'
# 遍历指定文件夹中的所有 txt 文件
txt_files = [f for f in os.listdir(txt_folder) if f.endswith('.txt')]
# 循环处理每个 txt 文件,并将结果写入 csv 文件
with open(csv_file, 'w', newline='') as out_file:
writer = csv.writer(out_file)
for txt_file in txt_files:
with open(os.path.join(txt_folder, txt_file), 'r') as in_file:
lines = in_file.readlines()
for line in lines:
row = line.strip().split(' ')
writer.writerow(row)
```
这里使用了 `os` 模块来遍历指定文件夹中的所有 txt 文件,然后使用 `csv` 模块来将每个文件的数据写入到 CSV 文件中。注意,这里的 `newline=''` 参数是为了避免在 Windows 系统下出现多余的空行。
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045021.png)