【问题标题】:Python CSV: Append to COLUMN, duplicate entriesPython CSV:追加到 COLUMN,重复条目
【发布时间】:2018-01-11 12:48:18
【问题描述】:

我正在尝试写入 CSV 文件,将每个新条目写入一列,但每次 CSV 文件都有重复条目。我只想在不存在的情况下创建第 1、2、3 行,作为第一行,然后将数据添加到第 1、2 和 3 列。 我有当前的代码:

import _csv

myData = [[1, 2, 3], ['Good Morning', 'Good Evening', 'Good Afternoon']]
myFile = open('csvexample3.csv', 'a')
with myFile:
   writer = _csv.writer(myFile)
   writer.writerows(myData)

我得到的结果:

1,2,3
Good Morning,Good Evening,Good Afternoon
1,2,3
Good Morning,Good Evening,Good Afternoon
1,2,3
Good Morning,Good Evening,Good Afternoon

如果它们存在,我只希望脚本创建 1、2 和 3 列,否则我想将文件附加到这些行。该脚本将是一个函数,因此它需要检查列是否存在并附加到它们。

【问题讨论】:

  • 请编辑问题以显示您想要的输出。

标签: python python-2.7 csv


【解决方案1】:

试试下面的代码。解释被添加为 cmets:

myData = [[1, 2, 3], ['Good Morning', 'Good Evening', 'Good Afternoon']]

# CREATE DATA FIRST AND THEN ADD IT TO FILE: 
dd = []     # an empty list to be filled with values to be added
dd.append(",".join(list(map(lambda x: str(x), myData[0])))) # add column header
for i in range(3):
    dd.append(",".join(myData[1]))          # add rows

# CHECK IF FILE EXIST AND THEN TAKE ACTION: 
import os
if os.path.exists("calling.txt"):   
    with open("calling.txt", 'a') as ff:    # create existing file for appending
        for i in dd[1:]:                    # omit adding header
            ff.write(i)
            ff.write("\n")
else: 
    with open("calling.txt", 'w') as ff:    # create new file for writing
        for i in dd:                        # add rows including header
            ff.write(i)
            ff.write("\n")

【讨论】:

    猜你喜欢
    • 2011-12-02
    • 2020-08-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-22
    • 2020-08-04
    • 2019-04-06
    • 2017-02-06
    相关资源
    最近更新 更多