我试图添加一个新行到我的旧CSV文件。基本上,每次运行Python脚本时它都会更新。

现在,我将旧的CSV行值存储在一个列表中,然后删除CSV文件,并再次使用新的列表值创建它。

我想知道有没有更好的方法。


当前回答

# I like using the codecs opening in a with 
field_names = ['latitude', 'longitude', 'date', 'user', 'text']
with codecs.open(filename,"ab", encoding='utf-8') as logfile:
    logger = csv.DictWriter(logfile, fieldnames=field_names)
    logger.writeheader()

# some more code stuff 

    for video in aList:
        video_result = {}                                     
        video_result['date'] = video['snippet']['publishedAt']
        video_result['user'] = video['id']
        video_result['text'] = video['snippet']['description'].encode('utf8')
        logger.writerow(video_result) 

其他回答

如果你使用pandas,你可以用这种方式将你的数据帧附加到一个现有的CSV文件中:

df.to_csv('log.csv', mode='a', index=False, header=False)

使用mode='a',我们确保我们附加,而不是覆盖;使用header=False,我们确保我们只附加df行的值,而不是header +值。

with open('document.csv','a') as fd:
    fd.write(myCsvRow)

使用'a'参数打开文件允许您在文件末尾追加内容,而不是简单地覆盖现有内容。试试。

# I like using the codecs opening in a with 
field_names = ['latitude', 'longitude', 'date', 'user', 'text']
with codecs.open(filename,"ab", encoding='utf-8') as logfile:
    logger = csv.DictWriter(logfile, fieldnames=field_names)
    logger.writeheader()

# some more code stuff 

    for video in aList:
        video_result = {}                                     
        video_result['date'] = video['snippet']['publishedAt']
        video_result['user'] = video['id']
        video_result['text'] = video['snippet']['description'].encode('utf8')
        logger.writerow(video_result) 

如果文件存在并且包含数据,那么可以为csv生成fieldname参数。DictWriter自动:

# read header automatically
with open(myFile, "r") as f:
    reader = csv.reader(f)
    for header in reader:
        break

# add row to CSV file
with open(myFile, "a", newline='') as f:
    writer = csv.DictWriter(f, fieldnames=header)
    writer.writerow(myDict)

我使用以下方法在.csv文件中添加新行:

pose_x = 1 
pose_y = 2

with open('path-to-your-csv-file.csv', mode='a') as file_:
    file_.write("{},{}".format(pose_x, pose_y))
    file_.write("\n")  # Next line.

【注意】:

Mode ='a'是追加模式。