python批量将txt转为csv
时间: 2023-09-04 22:06:52 浏览: 230
好的,可以使用Python中的pandas库来实现批量将txt文件转为csv文件的操作。具体步骤可以参考以下代码:
```python
import os
import pandas as pd
# 设置源文件目录和目标文件目录
source_dir = "./source/"
target_dir = "./target/"
# 遍历源文件目录中的所有txt文件,逐个进行转换
for filename in os.listdir(source_dir):
if filename.endswith(".txt"):
# 读取txt文件并转为DataFrame格式
file_path = os.path.join(source_dir, filename)
df = pd.read_csv(file_path, sep="\t")
# 生成目标文件路径并保存为csv格式
target_path = os.path.join(target_dir, filename.replace(".txt", ".csv"))
df.to_csv(target_path, index=False)
```
代码中首先设置了源文件目录和目标文件目录,然后使用os库的listdir()函数遍历源文件目录中的所有txt文件。对于每一个txt文件,我们使用pandas库的read_csv()函数读取为DataFrame格式,并将其保存为csv格式,最终存储到目标文件目录中。
以上是批量将txt转为csv的Python代码,希望能对您有所帮助。
阅读全文
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![7z](https://img-home.csdnimg.cn/images/20241231044736.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.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)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![-](https://img-home.csdnimg.cn/images/20241231044736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)