【发布时间】:2016-11-17 21:38:53
【问题描述】:
我有超过 2000 个 .txt 文件需要转换为 .csv 文件。每个都按顺序标记(即 nstar0001.txt、nstar0002.txt 等...)。我在多个地方搜索了答案,但通常解决方案是针对 Python2.x 或使用过时的库。每个星形文件有 7 列数据,我想在转换为 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 帖子可能会对您有所帮助 stackoverflow.com/questions/32659552/… 或者您可以从 github github.com/nschloe/matplotlib2tikz/issues/20 尝试此操作
标签: python-3.x csv