【问题标题】:How to convert multiple CSV files in directory to pipe-delimited text files using Python3如何使用 Python3 将目录中的多个 CSV 文件转换为管道分隔的文本文件
【发布时间】:2018-05-24 22:48:23
【问题描述】:

所以我是 Python(3) 的新手,需要创建一个循环,该循环将遍历近 200 个 CSV 文件,并将它们每个转换为一个以管道分隔的 .txt 文件(具有相同的名称)。

我有代码可以为 1 个文件执行此操作并且运行良好:

import csv

with open('C:/Path/InputFile.csv', 'r') as fin, \
open('C:/Path/OutputFile.txt', 'w') as fout:
reader = csv.DictReader(fin)
writer = csv.DictWriter(fout, reader.fieldnames, delimiter='|')
writer.writeheader()
writer.writerows(reader)

提前致谢。

【问题讨论】:

    标签: python-3.x loops csv


    【解决方案1】:

    您可以将代码修改为:

     for in_name, out_name in zip(list_of_in_names, list_of_out_names):
         with open(in_name, 'r') as fin, open(out_name, 'w') as fout:
             ...
    

    list_of_in_nameslist_of_out_names 分别是您要读取和写入的文件的名称。

    编辑:要解决 cmets 的问题,您可以使用 pathlib 库:

    from pathlib import Path
    
    for in_path in Path('C:/Path').glob('*.csv'):
         out_path = in_path.with_suffix('.txt')
         with in_path.open('r') as fin, out_path.open('w') as fout:
             ...
    

    【讨论】:

    • 谢谢戴维斯,但我一直在寻找一个循环,它可以自己遍历目录中的文件,而不是我必须创建一个列表。
    猜你喜欢
    • 2023-03-15
    • 1970-01-01
    • 2019-05-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多