import csv
from pathlib import Path
from concurrent.futures import ThreadPoolExecutor
def worker(file, csv_file):
print(f'converting file: {file} -> {csv_file}')
with open(file, newline=None) as IN, open(csv_file, 'w', newline=None) as OUT:
next(IN) # throwaway first line
headers = next(IN).strip().split(maxsplit=1) # adjust if files vary
rows = (row for row in csv.reader(IN, delimiter=' '))
csv.writer(OUT).writerows((headers, *rows))
print(f'done converting file: {file} -> {csv_file}')
with ThreadPoolExecutor(10) as e:
# adjust your path accordingly
for file in Path('.').glob('*.txt'):
csv_file = f'{file.stem}.csv'
e.submit(worker, file, csv_file)
2条答案
按热度按时间pnwntuvh1#
您可以使用
pandas
Python库来实现此目的。为了读取文本文件并将其保存为
csv
,您可以这样做:为了对多个文件自动执行此操作,您可以将它们全部存储在一个文件夹中,然后循环它们并在循环中调用上面的函数
txt_to_csv
,有点像这样:此脚本将使用相同的文件名以
.csv
将它们全部保存在同一文件夹中6qftjkof2#
如果每个文件的标题不同,你必须调整。而且,我是多线程的新手,这可能是矫枉过正。
https://onlinegdb.com/5S2R-yjpD