在python中的csv文件中添加新行到输出

时间:2017-12-30 02:59:00

标签: python csv

我是Python&的新手我有一个Web scraper程序,它检索链接并将它们放入.csv文件中。我需要在输出中的每个Web链接后添加一个新行,但我不知道如何正确使用\ n。这是我的代码:

  file = open('C:\Python34\census_links.csv', 'a')
  file.write(str(census_links))  
  file.write('\n')

2 个答案:

答案 0 :(得分:2)

如果不知道变量census_links的格式,很难回答您的问题。

但假设它是list包含由strings组成的多个链接,您可能希望解析列表中的每个链接并在给定链接的末尾附加换行符然后将该链接+换行符写入输出文件:

file = open('C:/Python34/census_links.csv', 'a')

# Simulating a list of links:
census_links = ['example.com', 'sample.org', 'xmpl.net']

for link in census_links: 
    file.write(link + '\n')       # append a newline to each link
                                  # as you process the links

file.close()         # you will need to close the file to be able to 
                     # ensure all the data is written.

答案 1 :(得分:2)

E. Ducateme已经回答了问题,但您也可以使用csv模块(大部分代码来自here):

import csv

# This is assuming that “census_links” is a list
census_links = ["Example.com", "StackOverflow.com", "Google.com"]
file = open('C:\Python34\census_links.csv', 'a')
writer = csv.writer(file)

for link in census_links:
    writer.writerow([link])