【问题标题】:use python to write to a specific column is a .csv file使用 python 写入特定列是一个 .csv 文件
【发布时间】:2017-10-06 23:12:00
【问题描述】:

我有一个 .csv 文件,我需要用列表中的新值覆盖某个列。

假设我有一个列表 L1 = ['La', 'Lb', 'Lc'] 我想写在第 1 列中。 .csv 文件的 5 个。

如果我跑步:

L1 = ['La', 'Lb', 'Lc']
import csv
with open(r'C:\LIST.csv','wb') as f:
    w = csv.writer(f)
    for i in L1:
        w.writerow(i)

这会将 L1 值写入第一列和第二列。

第一列为'L'、'L'、'L',第二列为'a'、'b'、'c'

我找不到将列表中每个元素写入特定列的语法。 (这是在 Python 2.7 中)。感谢您的帮助!

(对于这个脚本,我必须使用 IronPython,并且只使用 IronPython 附带的内置库)

【问题讨论】:

  • 可以结合读写。从源文件中读取每一行,对某些列应用更改并将其写入目标文件,最后将目标文件重命名为源文件。
  • 谢谢。我知道该怎么做,但我不知道如何将我的列表写入 .csv 中的特定列

标签: python-2.7 csv


【解决方案1】:

虽然您当然可以使用 Python 的内置 csv 模块来读取、修改和写出数据,但我还是推荐优秀的 tablib 模块:

from tablib import Dataset

csv = '''Col1,Col2,Col3,Col4,Col5,Col6,Col7
a1,b1,c1,d1,e1,f1,g1
a2,b2,c2,d2,e2,f2,g2
a3,b3,c3,d3,e3,f3,g3
'''

# Read a hard-coded string just for test purposes.
# In your code, you would use open('...', 'rt').read() to read from a file.
imported_data = Dataset().load(csv, format='csv')

L1 = ['La', 'Lb', 'Lc']

for i in range(len(L1)):
    # Each row is a tuple, and tuples don't support assignment.
    # Convert to a list first so we can modify it.
    row = list(imported_data[i])

    # Put our value in the 5th column (index 4).
    row[4] = L1[i]

    # Store the row back into the Dataset.
    imported_data[i] = row

# Export to CSV. (Of course, you could write this to a file instead.)
print imported_data.export('csv')

# Output:
# Col1,Col2,Col3,Col4,Col5,Col6,Col7
# a1,b1,c1,d1,La,f1,g1
# a2,b2,c2,d2,Lb,f2,g2
# a3,b3,c3,d3,Lc,f3,g3

【讨论】:

  • 再次感谢。不幸的是,这个脚本必须在 IronPython 上运行,所以这就是我提到 Python 2.7 的原因,因为 IronPython 类似于 2.7(所以没有 Pandas 等)。我只能在 IronPython 中使用默认库。
  • tablib 在某种程度上与 IronPython 不兼容吗?或者为什么只能使用内置库?
  • 感谢您的建议/提问。该脚本将在我无权(我被允许)安装特定库或进行任何其他自定义的计算机上运行。所以我必须使用默认安装的带有 IronPython 的东西。 “tablib”不在 IronPython 的 Lib 文件夹中。
  • 请使用此约束编辑您的问题,以便其他尝试回答的人知道您只能使用内置库。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-10-25
  • 1970-01-01
  • 1970-01-01
  • 2021-05-27
  • 1970-01-01
相关资源
最近更新 更多