我是Python&的新手我有一个Web scraper程序,它检索链接并将它们放入.csv文件中。我需要在输出中的每个Web链接后添加一个新行,但我不知道如何正确使用\ n。这是我的代码:
file = open('C:\Python34\census_links.csv', 'a')
file.write(str(census_links))
file.write('\n')
答案 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])