.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'
를 얻을 수 있지만, 그냥 모든 파일을 실행하기 전에 작업을 진행하고 싶었다.
'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