[英]Add new line to output in csv file in python
I am a newbie at Python & I have a web scraper program that retrieved links and puts them into a .csv file. 我是Python的新手,我有一个网络抓取程序,可以检索链接并将其放入.csv文件中。 I need to add a new line after each web link in the output but I do not know how to use the \\n properly.
我需要在输出中的每个Web链接之后添加新行,但是我不知道如何正确使用\\ n。 Here is my code:
这是我的代码:
file = open('C:\Python34\census_links.csv', 'a')
file.write(str(census_links))
file.write('\n')
Hard to answer your question without knowing the format of the variable census_links
. 不知道变量
census_links
的格式就很难回答您的问题。
But presuming it is a list
that contains multiple links composed of strings
, you would want to parse through each link in the list and append a newline character to the end of a given link and then write that link + newline to the output file: 但是假设它是一个包含由
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.
E. Ducateme has already answered the question, but you could also use the csv module (most of the code is from here ): E. Ducateme已经回答了这个问题,但是您也可以使用csv模块(大多数代码是从此处 ):
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])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.