티스토리 뷰

반응형

Stack Overflow에 자주 검색, 등록되는 문제들과 제가 개발 중 찾아 본 문제들 중에서 나중에도 찾아 볼 것 같은 문제들을 정리하고 있습니다.

Stack Overflow에서 가장 먼저 확인하게 되는 가장 높은 점수를 받은 Solution과 현 시점에 도움이 될 수 있는 가장 최근에 업데이트(최소 점수 확보)된 Solution을 각각 정리하였습니다.

 

아래 word cloud를 통해 이번 포스팅의 주요 키워드를 미리 확인하세요.

Writing a Python list of lists to a csv file

파이썬 리스트를 csv 파일에 쓰기

 문제 내용 

I have a long list of lists of the following form ---

저는 다음과 같은 형식의 긴 리스트가 많이 있습니다 ---
a = [[1.2,'abc',3],[1.2,'werew',4],........,[1.4,'qew',2]]

 

i.e. the values in the list are of different types -- float,int, strings.How do I write it into a csv file so that my output csv file looks like

즉, 리스트의 값은 float, int, 문자열과 같은 다른 유형입니다. 출력 csv 파일이 다음과 같이 보이도록 csv 파일에 쓰는 방법을 알려주세요.
1.2,abc,3
1.2,werew,4
.
.
.
1.4,qew,2

 

 

 높은 점수를 받은 Solution 

Python's built-in CSV module can handle this easily:

파이썬의 내장 CSV 모듈이 쉽게 처리할 수 있습니다.
import csv

with open("output.csv", "wb") as f:
    writer = csv.writer(f)
    writer.writerows(a)

 

This assumes your list is defined as a, as it is in your question. You can tweak the exact format of the output CSV via the various optional parameters to csv.writer() as documented in the library reference page linked above.

이는 질문에서와 같이 a로 정의된 리스트를 전제로합니다. 위에서 링크된 라이브러리 참조 페이지에서 csv.writer()에 대한 다양한 선택적 매개 변수를 통해 출력 CSV의 정확한 형식을 조정할 수 있습니다.

 

Update for Python 3

Python 3 업데이트
import csv

with open("out.csv", "w", newline="") as f:
    writer = csv.writer(f)
    writer.writerows(a)

 

 

 가장 최근 달린 Solution 

If you don't want to import csv module for that, you can write a list of lists to a csv file using only Python built-ins

csv 모듈을 가져 오지 않으려면 Python 내장 기능 만 사용하여 목록의 목록을 CSV 파일에 작성할 수 있습니다.
with open("output.csv", "w") as f:
    for row in a:
        f.write("%s\n" % ','.join(str(col) for col in row))

 

 

출처 : https://stackoverflow.com/questions/14037540/writing-a-python-list-of-lists-to-a-csv-file

반응형
댓글
공지사항
최근에 올라온 글