【发布时间】:2020-12-13 16:08:43
【问题描述】:
我编写了一个 python 代码,它将输入一个 txt 文件并打印到 excel 。我能够实现一个 txt 文件作为输入。但是我的要求是在一个文件夹中有大约一百万个 txt 文件。所以我不知道如何更改 python 代码以从文件夹中获取输入。
以下代码处理输入 1.txt 文件。我想从一个文件夹中运行多个 txt 文件,这是我的要求。
with open('C:/test/1.txt') as infile:
registrations = []
fields = OrderedDict()
d = {}
for line in infile:
line = line.strip()
if line:
key, value = [s.strip() for s in line.split(':', 1)]
d[key] = value
fields[key] = None
else:
if d:
registrations.append(d)
print(d)
d = {}
if ',' not in line:
print('line without ,:', line)
continue
else:
if d: # handle EOF
registrations.append(d)
with open('C:/registrations.csv', 'w') as outfile:
writer = DictWriter(outfile, fieldnames=fields)
writer.writeheader()
writer.writerows(registrations)
谢谢, 米拉
【问题讨论】: