【发布时间】:2018-06-10 08:44:03
【问题描述】:
我是 Python 的新手,我有一个网络爬虫程序,可以检索链接并将它们放入 .csv 文件中。我需要在输出中的每个 Web 链接后添加一个新行,但我不知道如何正确使用 \n。这是我的代码:
file = open('C:\Python34\census_links.csv', 'a')
file.write(str(census_links))
file.write('\n')
【问题讨论】:
我是 Python 的新手,我有一个网络爬虫程序,可以检索链接并将它们放入 .csv 文件中。我需要在输出中的每个 Web 链接后添加一个新行,但我不知道如何正确使用 \n。这是我的代码:
file = open('C:\Python34\census_links.csv', 'a')
file.write(str(census_links))
file.write('\n')
【问题讨论】:
在不知道变量census_links 的格式的情况下很难回答您的问题。
但假设它是一个包含多个由strings 组成的链接的list,您可能希望解析列表中的每个链接并将换行符附加到给定链接的末尾,然后编写该链接 +输出文件的换行符:
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.
【讨论】:
print(x, file=f) 是f.write(x + '\n') 的另一种方式。
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])
【讨论】: