如何逐行写入CSV?

pw9qyyiw  于 2023-03-27  发布在  其他
关注(0)|答案(6)|浏览(192)

我有通过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)
djp7away

djp7away1#

一般方式:

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

ylamdve62#

您可以像写入任何普通文件一样写入该文件。

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

qnyhuwrf3#

我会简单地将每一行写入一个文件,因为它已经是CSV格式:

write_file = "output.csv"
with open(write_file, "wt", encoding="utf-8") as output:
    for line in text:
        output.write(line + '\n')

我不记得如何写行与分行的时刻,虽然:p
另外,您可能想了解一下this answer,了解一下write()writelines()'\n'

9bfwbjaz

9bfwbjaz4#

除了前面的答案,我创建了一个快速写入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()))

玩得开心

7y4bm7vi

7y4bm7vi5#

这个怎么样

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

返回一个字符串,它是iterable中字符串的串联。元素之间的分隔符是提供此方法的字符串。

6mw9ycah

6mw9ycah6#

在我的情况下...

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)

您需要在open属性中包含newline选项,它才能正常工作
https://www.programiz.com/python-programming/writing-csv-files

相关问题