2016-07-14 6 views
1

.csv 파일로 변환해야하는 2000 개 이상의 .txt 파일이 있습니다. 각 광고는 순차적으로 라벨이 지정됩니다 (예 : nstar0001.txt, nstar0002.txt 등). 여러 곳에서 답변을 검색했지만 해결책은 Python2.x 또는 오래된 라이브러리를 사용하는 경우가 많습니다. 각 별 파일에는 CSV 형식으로 변환 할 때 레이블을 지정해야하는 7 개의 데이터 열이 있습니다.파이썬 3에서 여러 텍스트 파일을 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'을 사용하십시오. 이 게시물은 http://stackoverflow.com/questions/32659552/izip-not-working-in-python-3-x 또는 github https://github.com/nschloe/matplotlib2tikz/에서 시도 할 수 있습니다. issues/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에서 시작됩니다. 어떻게하면 그것을 높이 시작할 수 있을까요? [편집] while 루프로 얻었습니다. 도와 주셔서 감사합니다! 매력처럼 작동합니다. – Justin

+0

Range는 또한 시작 값을 취합니다 : range (1, N)은 당신이 원하는 것을 할 것입니다. –

+0

while 루프를 사용하면 어떤 이점이 있습니까? – Justin

관련 문제