Nice programing

Python은 한 줄씩 CSV에 쓰기

nicepro 2020. 10. 23. 18:57
반응형

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)

일반적인 방법 :

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

일반 파일을 쓰는 것처럼 파일에 쓸 수 있습니다.

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)

이미 CSV 형식이므로 각 줄을 파일에 작성합니다.

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

I can't recall how to write lines with line-breaks at the moment, though :p

Also, you might like to take a look at this answer about write(), writelines(), and '\n'.


What about this:

with open("your_csv_file.csv", "w") as f:
    f.write("\n".join(text))

str.join() Return a string which is the concatenation of the strings in iterable. The separator between elements is the string providing this method.


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.

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

참고URL : https://stackoverflow.com/questions/37289951/python-write-to-csv-line-by-line

반응형