2016-07-14 177 views
1

我刚刚超过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' 

我知道这个循环只适用于前几个文件,但只是想获得它运行它的所有文件之前工作。

+0

'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

回答

0

您可以使用熊猫。像这样的东西应该工作:

import pandas as pd 

for i in range(5): 
    fln = "nstar%04d" % i 
    df = pd.read_csv(fln+".txt",delim_whitespace=True, header=None) 
    hdr = ['jd', 'mag', 'merr', 'id', 'cerr', 'serr', 'perr'] 
    df.to_csv(fln+".csv", header=hdr, index=False) 
+0

使用for循环启动搜索nstar0000.txt的脚本,但是我的数据从nstar0001.txt开始。我该如何改变这种情况才能创造更高的价值。 [编辑]有一段时间了。谢谢您的帮助!奇迹般有效。 – Justin

+0

范围也将采取一个起始值:范围(1,N)将做你想要的。 –

+0

在while循环中使用它的好处是什么? – Justin

相关问题