티스토리 뷰

개발/파이썬

CSV 파일 한 줄씩 작성하기

맨날치킨 2023. 2. 3. 16:05
반응형

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

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

 

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

How to write to a CSV line by line?

어떻게 CSV를 한 줄씩 작성할 수 있나요?

 문제 내용 

I have data which is being accessed via http request and is sent back by the server in a comma separated format, I have the following code :

HTTP 요청을 통해 액세스되는 데이터가 있고, 서버에서 쉼표로 구분된 형식으로 반환됩니다. 다음 코드가 있습니다:
site= 'www.example.com'
hdr = {'User-Agent': 'Mozilla/5.0'}
req = urllib2.Request(site,headers=hdr)
page = urllib2.urlopen(req)
soup = BeautifulSoup(page)
soup = soup.get_text()
text=str(soup)

 

The content of text is as follows:

text의 내용은 다음과 같습니다.
april,2,5,7
may,3,5,8
june,4,7,3
july,5,6,9

 

How can I save this data into a CSV file. I know I can do something along the lines of the following to iterate line by line:

이 데이터를 CSV 파일에 저장하는 방법은 무엇인가요? 각 줄을 반복하려면 다음과 같은 내용을 할 수 있습니다.
import StringIO
s = StringIO.StringIO(text)
for line in s:

 

But i'm unsure how to now properly write each line to CSV

하지만 이제 각 줄을 CSV에 적절하게 작성하는 방법이 분명하지 않습니다.

 

EDIT---> Thanks for the feedback as suggested the solution was rather simple and can be seen below.

EDIT---> 피드백 감사합니다. 제안된 대로, 해결책은 꽤 간단하며 아래에서 확인할 수 있습니다.

 

Solution:

해결책:
import StringIO
s = StringIO.StringIO(text)
with open('fileName.csv', 'w') as f:
    for line in s:
        f.write(line)

 

 

 높은 점수를 받은 Solution 

General way:

일반적인 방법:
##text=List of strings to be written to file
with open('csvfile.csv','wb') as file:
    for line in text:
        file.write(line)
        file.write('\n')

 

OR

또는

 

Using CSV writer :

CSV 작성자 사용 :
import csv
with open(<path to output_csv>, "wb") as csv_file:
        writer = csv.writer(csv_file, delimiter=',')
        for line in data:
            writer.writerow(line)

 

OR

또는

 

Simplest way:

가장 간단한 방법:
f = open('csvfile.csv','w')
f.write('hi there\n') #Give your csv text here.
## Python will convert \n to os.linesep
f.close()

 

 

 가장 최근 달린 Solution 

To complement the previous answers, I whipped up a quick class to write to CSV files. It makes it easier to manage and close open files and achieve consistency and cleaner code if you have to deal with multiple files.

이전 답변을 보완하기 위해, CSV 파일에 작성하기 위한 빠른 클래스를 만들었습니다. 파일을 열고 닫고 일관성 있고 더 깨끗한 코드를 만드는 데 도움이 됩니다.
class CSVWriter():

    filename = None
    fp = None
    writer = None

    def __init__(self, filename):
        self.filename = filename
        self.fp = open(self.filename, 'w', encoding='utf8')
        self.writer = csv.writer(self.fp, delimiter=';', quotechar='"', quoting=csv.QUOTE_ALL, lineterminator='\n')

    def close(self):
        self.fp.close()

    def write(self, elems):
        self.writer.writerow(elems)

    def size(self):
        return os.path.getsize(self.filename)

    def fname(self):
        return self.filename

 

Example usage:

예시 사용법:
mycsv = CSVWriter('/tmp/test.csv')
mycsv.write((12,'green','apples'))
mycsv.write((7,'yellow','bananas'))
mycsv.close()
print("Written %d bytes to %s" % (mycsv.size(), mycsv.fname()))

 

Have fun

즐거운 시간 되세요

 

 

 

출처 : https://stackoverflow.com/questions/37289951/how-to-write-to-a-csv-line-by-line

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