Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/string/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何逐行写入CSV?_Python_String_File_Csv_Io - Fatal编程技术网

Python 如何逐行写入CSV?

Python 如何逐行写入CSV?,python,string,file,csv,io,Python,String,File,Csv,Io,我有通过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

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

我只需将每一行写入一个文件,因为它已经是CSV格式:

write_file = "output.csv"
with open(write_file, "w") as output:
    for line in text:
        output.write(line + '\n')
不过,我现在记不起如何用换行符写行了:p


另外,您可能想了解一下关于
write()
writelines()
、和
'\n'

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

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)
一般方法:

##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)
那么这个呢:

with open("your_csv_file.csv", "w") as f:
    f.write("\n".join(text))
返回一个字符串,该字符串是iterable中字符串的串联。 元素之间的分隔符是 提供此方法的字符串


为了补充前面的答案,我创建了一个快速类来编写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
用法示例:

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

玩得开心

它已经是一个CSV,您只需将每一行写入一个文件……老实说,我不确定您是否需要
StringIO
导入。另外,按原样的解决方案可能不会分隔行,因为
f.write()
不会自动追加换行。@icedwater我明白你的意思,但我运行了上面的代码,它能够正确地将数据存储到csv文件中。另请参见:对于python 3,使用open(,“w”,newline='')将其更改为
作为csv\u文件:
此行缺少信息
对于数据中的行:
。请把它修好。谢谢。@gsamaras这个想法是为了帮助社区,不像你编辑和评论那样没用。如果csv文件中已经有内容,如何使用第三种解决方案追加一行?@JürgenK。使用
'a'
(追加模式)代替
'w'
(写入模式)。
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()))