복붙노트

[PYTHON] 파이썬은 라인 단위로 CSV를 작성합니다.

PYTHON

파이썬은 라인 단위로 CSV를 작성합니다.

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)

텍스트의 내용은 다음과 같습니다.

april,2,5,7
may,3,5,8
june,4,7,3
july,5,6,9

이 데이터를 어떻게 CSV 파일에 저장할 수 있습니까? 줄 단위로 반복하기 위해 다음 행을 따라 뭔가를 할 수 있다는 것을 알고 있습니다.

import StringIO
s = StringIO.StringIO(text)
for line in s:

하지만 어떻게 지금 CSV에 제대로 각 라인을 작성하는지 모르겠습니다.

편집 --- 솔루션 제안은 다소 간단하고 아래에서 볼 수 있듯이 의견을 보내 주셔서 감사합니다.

해결책:

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

해결법

  1. ==============================

    1.일반적인 방법 :

    일반적인 방법 :

    ##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')
    

    또는

    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)
    

    또는

    가장 간단한 방법 :

    f = open('csvfile.csv','w')
    f.write('hi there\n') #Give your csv text here.
    ## Python will convert \n to os.linesep
    f.close()
    
  2. ==============================

    2.일반 파일을 쓰듯이 파일에 쓸 수 있습니다.

    일반 파일을 쓰듯이 파일에 쓸 수 있습니다.

    with open('csvfile.csv','wb') as file:
        for l in text:
            file.write(l)
            file.write('\n')
    

    만약에 대비해 목록의 목록이라면, 직접 내장 된 CSV 모듈을 사용할 수 있습니다.

    import csv
    
    with open("csvfile.csv", "wb") as file:
        writer = csv.writer(file)
        writer.writerows(text)
    
  3. ==============================

    3.이미 CSV 형식이므로 파일에 각 행을 씁니다.

    이미 CSV 형식이므로 파일에 각 행을 씁니다.

    write_file = "output.csv"
    with open(write_file, "w") as output:
        for line in text:
            output.write(line + '\n')
    

    나는 줄 바꿈이있는 줄을 지금 쓰는 방법을 기억하지 못한다. : p

    또한 write (), writelines () 및 '\ n'에 대한 대답을 살펴볼 수도 있습니다.

  4. ==============================

    4.이건 어때?

    이건 어때?

    with open("your_csv_file.csv", "w") as f:
        f.write("\n".join(text))
    
  5. from https://stackoverflow.com/questions/37289951/python-write-to-csv-line-by-line by cc-by-sa and MIT license