sourcetip

CSV에 한 줄씩 쓰는 방법은 무엇입니까?

fileupload 2023. 8. 16. 22:34
반응형

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에 올바르게 쓰는 방법을 잘 모르겠습니다.

EDIT---> 솔루션이 다소 단순하고 아래와 같이 제안된 피드백에 감사드립니다.

솔루션:

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

OR

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

가장 간단한 방법:

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, "wt", encoding="utf-8") as output:
    for line in text:
        output.write(line + '\n')

하지만 지금은 줄 바꿈으로 줄을 어떻게 쓰는지 기억이 안 나요 :p

또한, 당신은 이 대답을 보는 것이 좋을 것입니다.write(),writelines(),그리고.'\n'.

이전 답변 외에도 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, *args):
        self.writer.writerow(args)

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

    def fname(self):
        return self.filename

사용 예:

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

즐겁게 보내세요

다음은 어떻습니까?

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

str.join() 시작 가능한 문자열의 연결인 문자열을 반환합니다.요소 사이의 구분 기호는 이 메서드를 제공하는 문자열입니다.

내 상황에선...

  with open('UPRN.csv', 'w', newline='') as out_file:
    writer = csv.writer(out_file)
    writer.writerow(('Name', 'UPRN','ADMIN_AREA','TOWN','STREET','NAME_NUMBER'))
    writer.writerows(lines)

당신은 그것을 포함해야 합니다.newline의 옵션open속성과 그것은 작동할 것입니다.

https://www.programiz.com/python-programming/writing-csv-files

언급URL : https://stackoverflow.com/questions/37289951/how-to-write-to-a-csv-line-by-line

반응형