【问题标题】:Add new line to output in csv file in python在python的csv文件中添加新行输出
【发布时间】: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


    【解决方案1】:

    在不知道变量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') 的另一种方式。
    • @MadPhysicist ...你说的绝对是真的,谢谢分享。我选择尽量接近 OP 的原始代码布局,以尽量减少认知负担。
    • 这可能是个好主意。我将在这里留下评论以供后代使用。
    • 非常感谢!这些是在一组中,但效果很好。
    【解决方案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])
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-04-08
      • 1970-01-01
      • 2018-05-20
      • 2012-07-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多