我刚刚超过2000个.txt文件,我需要转换为.csv文件。每个都按顺序标记(即nstar0001.txt,nstar0002.txt等)。我搜索了多个地方的答案,但通常解决方案是针对Python2.x或使用过期的库。每个星形文件都有7列数据,当转换为csv格式时,我想标记这些数据。如何在Python3中将多个文本文件转换为csv格式?
这是我最近一次尝试:
import csv
import os
import itertools
##Convert all nstar####.txt files to csv
stars = int(input("Enter the TOTAL number of stars (including 'bad' stars):"))
k = 1
while k < stars + 1:
if k < 10:
q = 'nstar' + '0' + '0' + '0' + str(k) + '.txt'
r = 'nstar' + '0' + '0' + '0' + str(k) + '.csv'
with open(q, 'rb') as in_file:
stripped = (line.strip() for line in in_file)
lines = (line for line in stripped if line)
grouped = itertools.izip(*[lines] * 7)
with open(r, 'wb') as out_file:
writer = csv.write(out_file)
writer.writerow(('jd', 'mag', 'merr', 'id', 'cerr', 'serr', 'perr'))
writer.writerows(grouped)
这是从另一个StackOverflow的问题,借用和略作修改,以满足我的需求。然而,在运行我得到
AttributeError: module 'itertools' has no attribute 'izip'
我知道这个循环只适用于前几个文件,但只是想获得它运行它的所有文件之前工作。
'izip'是在Python-2.x。在Python-3.x上使用'zip'。这个SO帖子可能会帮助你http://stackoverflow.com/questions/32659552/izip-not-working-in-python-3-x或者你可以尝试从github https://github.com/nschloe/matplotlib2tikz/问题/ 20 – alvits