【问题标题】:Writing to CSV file choosing the column to write in写入 CSV 文件,选择要写入的列
【发布时间】:2019-10-19 16:13:18
【问题描述】:

我正在尝试从包含一些关于文本的数据的 X(在本例中为 6 个)CSV 文件导入数据,并将每个文档中的一个特定行放到一个新行上,这样它们就会出现在每个文档旁边其他(从第 1 列的文档 1 导出,从第 2 行的第二个文档导出,依此类推)。到目前为止,我一直没有成功。

    # I have a list containing the path to all relevant files
    files = ["path1", "path2", ...]

    # then I tried cycling through the folder like this
    for file in files:
        with open(file, "r") as csvfile:
            reader = csv.reader(csvfile, delimiter=",")
            for row on reader:
                # I'm interested in the stuff stored on Column 2
                print([row[2]])
    # as you can see, I can get the info from the files, but from here 
    # on, I can't find a way to then write that information on the 
    # appropiate coloumn of the newly created CSV file

编辑:我知道如何打开编写器,但我不知道如何编写一个脚本,每次处理一个新文件时,该脚本将从原始 6 个文档中获取的信息写入不同的列。

【问题讨论】:

标签: python csv writing


【解决方案1】:
# I have a list containing the path to all relevant files
files = ["path1", "path2", ...]
newfile = "newpath1"

# then I tried cycling through the folder like this
for file in files:
    with open(file, "r") as csvfile:
        reader = csv.reader(csvfile, delimiter=",")
        with open(newfile, "a") as wcsvfile:
            writer = csv.writer(wcsvfile)
            for row on reader:
                # I'm interested in the stuff stored on Column 2
                writer.writerow([row[2]])

【讨论】:

  • 这不会为我处理的每个文件创建一个新文件吗?我宁愿创建一个存储所有内容的文件。问题是,如果我只是在那里添加一个 write() 函数,脚本会用新信息覆盖旧信息。
  • 使用 open(newfile, "a") 将追加数据。不会超车
猜你喜欢
  • 1970-01-01
  • 2018-08-10
  • 2014-01-10
  • 1970-01-01
  • 1970-01-01
  • 2016-09-26
  • 1970-01-01
相关资源
最近更新 更多