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

问题描述 投票:1回答:2

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

  file = open('C:\Python34\census_links.csv', 'a')
  file.write(str(census_links))  
  file.write('\n')
python csv
2个回答
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.

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])
© www.soinside.com 2019 - 2024. All rights reserved.