所以我是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)
提前致谢。
答案 0 :(得分:0)
您可以将代码修改为:
artist track_title lyric character
1 Claude-Michel Schönberg Prologue ["Work Song"] ["Work Song"]
2 Claude-Michel Schönberg Prologue [PRISONERS] [PRISONERS]
3 Claude-Michel Schönberg Prologue Aaah, aah, aaaahhhh [PRISONERS]
4 Claude-Michel Schönberg Prologue Don't look 'em in the eye false
5 Claude-Michel Schönberg Prologue Look down, look down false
6 Claude-Michel Schönberg Prologue You're here until you die false
7 Claude-Michel Schönberg Prologue [PRISONER #1] [PRISONER #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_names
个名称。
编辑:要解决评论中的问题,您可以使用list_of_out_names
库:
pathlib