首页 > 解决方案 > 如何从符合特定规则的 csv 中过滤出所有行并将它们写入 Python 中的新 csv?

问题描述

我有这个包含大量数据的 CSV,它基本上是一个图片、标签和坐标列表,如下所示:

TRAIN,gs://holo_newid/ML_NewID300004-2020-10-20T12:29:31.205Z.png,holo_rond,0.26313025,0.24606742,0.34716386,0.24606742,0.34716386,0.4247191,0.26313025,0.4247191

现在我剪掉NewID300004,这是图片的id。我希望 NewId 之后的所有带有 3 的行都转到一个名为 clip3.csv 的文件,我试试这个:

with open(r"./data/moving_light_frames/holo_labeled.csv", newline='') as csvfile:
# Reads CSV with the , seprator
reader = csv.reader(csvfile, delimiter=',')
# For every line in csv process
for row in reader:
    path = row[1]
    img_name = path.split('/')[4]
    img_name = img_name.split('-')[0]
    number = re.findall("[12345]",img_name)
    number = number[0]
    print(number)
    with open("./data/results/moving_light_frames/clip" + number, 'w', newline='') as csvfile:
        writer = csv.writer(csvfile, delimiter=',')
        writer.writerow([row[0], row[1], row[2], row[3], row[4], row[5], row[6], row[7], row[8], row[9], row[10]])

现在这确实将它写入具有该名称的csv,但只有一行......也许它每次都会覆盖第一行?也许不是,我不知道。我知道这似乎是一个愚蠢的问题,但如果有人能在正确的方向上给我一个轻推,我将非常感激。我对 Python 很陌生,而且每天都在学习更多。

标签: pythoncsvpycharm

解决方案


当然,当我发布问题时,我想出了答案。我会在这里张贴它的好措施。我必须做的唯一改变是:

with open("./data/results/moving_light_frames/clip" + number, 'w', newline='') as csvfile:

我也更改了附加模式(听起来也很酷!)

with open("./data/results/moving_light_frames/clip" + number, 'a+', newline='') as csvfile:

所以从'w'到'a+'


推荐阅读