在python中将列名写入csv文件(如果它们不存在)

5ktev3wc  于 2023-04-28  发布在  Python
关注(0)|答案(1)|浏览(161)

我的问题是,我需要创建一个csv文件与视频信息,将写入列名的第一行,然后附加行的信息,为每个视频上传。正如你在下面看到的,它将打开空白的csv文件videos.csv,然后检查第一行是否已经存在列名,如果不存在,它将写入它们,如果存在,它将继续并在下面附加视频信息。然而,当我运行这个时,csv文件是空白的,但它没有写入列名,它只会写入视频信息。

#check for column names
    with open('videos.csv', 'r') as csvfile:
        reader = csv.reader(csvfile)
        for row in reader:
            if row[0] in reader is not None:
                continue
            else:
                with open('videos.csv', 'w') as file:
                    writer = csv.writer(file)
                    writer.writerow(["id", "fileName", "videoName", "description", "genre"])
    
    #append video information
    with open('videos.csv', 'a') as f:
        writer = csv.writer(f)
        randomId = str(random.randint(1,1000000))
        fileName = os.path.basename(filePath)
        writer.writerow([randomId, fileName, videoName, description, genre])
alen0pnh

alen0pnh1#

举个简单的例子

import csv
import random 

with open('videos.csv', 'r+') as csvfile:
    reader = csv.reader(csvfile)
    if reader.line_num == 0:
        writer = csv.writer(csvfile)
        writer.writerow(["id", "fileName", "videoName", "description", "genre"])
    writer = csv.writer(csvfile)
    randomId = str(random.randint(1,1000000))
    writer.writerow([randomId, 'test', 'videoName', 'description', 'genre'])

cat videos.csv 
id,fileName,videoName,description,genre
996548,test,videoName,description,genre

相关问题