【问题标题】:How to write a list of path names on separate rows in csv file?如何在 csv 文件的不同行上编写路径名列表?
【发布时间】:2015-07-18 04:57:41
【问题描述】:

我有一个路径名列表:

li = [u"C:\\temp\\fileA.shp", u"C:\\temp\\fileB.shp", u"C:\\temp\\fileC.shp"]

我正在尝试将每个路径写入 txt 文件中的单独一行。这是我到目前为止所做的:

import csv

li = [u"C:\\temp\\fileA.shp", u"C:\\temp\\fileB.shp", u"C:\\temp\\fileC.shp"]

with open(r'C:\temp\myfile.csv', "wb") as f:
    wr = csv.writer(f, delimiter=',', quoting=csv.QUOTE_NONE)
    wr.writerows([li])

这会产生同一行的文件列表:

C:\temp\fileA.shp,C:\temp\fileB.shp,C:\temp\fileC.shp

我怎样才能调整它,使路径名都在自己的行上?以下是我所追求的:

C:\temp\fileA.shp
C:\temp\fileB.shp
C:\temp\fileC.shp

【问题讨论】:

  • 链接的问题有你的问题的答案。如果直接写入txt文件,则不需要使用CSV。

标签: python list csv


【解决方案1】:

只需添加\n 女巫意味着新

import csv

li = [u"C:\\temp\\fileA.shp", u"C:\\temp\\fileB.shp", u"C:\\temp\\fileC.shp"]

with open(r'C:\temp\myfile.txt', "wb") as f:
    wr = csv.writer(f + '\n', delimiter=',', quoting=csv.QUOTE_NONE)
    wr.writerows([li])

所以现在 f 将被打印 + \n (新行)

【讨论】:

  • 我收到一个错误:TypeError: unsupported operand type(s) for +: 'file' and 'str'
  • 抱歉,现在进行了更改。
  • 感谢您的帮助。不幸的是,我得到了同样的错误。
  • 你知道你想要一个列表。 Cvs 代表 Comma Sperated Vale。如果您想要一个列表,请将其设为 .txt
  • f 是一个文件对象,您尝试将'\n' 添加到它。
猜你喜欢
  • 2011-08-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-12-14
  • 1970-01-01
  • 2017-06-24
相关资源
最近更新 更多