Python 3.x 删除python中的特定行和相应文件

Python 3.x 删除python中的特定行和相应文件,python-3.x,csv,Python 3.x,Csv,我想删除90%的“转向”值等于0的行。并且有一个对应的图像文件用于所有三个f,中间、左侧和右侧。我也想删除它们。csv文件如下所示: 我已经编写了以下代码,以至少获取转向值为0的文件。我所需要的只是随机获取90%的文件并删除它们的代码 with open('data/driving_log.csv') as csvfile: reader = csv.reader(csvfile) for i,line in enumerate(reader): lines.ap

我想删除90%的“转向”值等于0的行。并且有一个对应的图像文件用于所有三个f,中间、左侧和右侧。我也想删除它们。csv文件如下所示:

我已经编写了以下代码,以至少获取转向值为0的文件。我所需要的只是随机获取90%的文件并删除它们的代码

with open('data/driving_log.csv') as csvfile:
    reader = csv.reader(csvfile)
    for i,line in enumerate(reader):
        lines.append(line)
        index.append(i)

lines = np.delete(lines,(0), axis = 0)
for i, line in enumerate(lines):
    #print(type(line[3].astype(np.float)))
    line_no.append(line[3].astype(np.float32))
    #print(line_no[i])
    if line_no[i]==0.0:
          # this gets the first column of the row.
        for j in range(3):
            source_path = line[j]
            filename = source_path.split('/')[-1]
            print(filename)
        count += 1

我想这会满足你的要求:

import csv
from random import randint
from os import remove

# Create a 2D list from which we can work with
lines = []
with open('data/driving_log.csv', newline='') as csvfile:
    reader = csv.reader(csvfile)
    for line in reader:
        lines.append(line)

# Find 10% of total lines (to keep), not including header row
numToKeep = round(sum(1 for i in lines if i[3] == '0') * 0.1)

# Save 10% of lines to a new 2D list
toKeep = []
for i in range(numToKeep):
    while True:
        index = randint(1, len(lines)-1)
        # Make sure we haven't already selected the same line
        if lines[index] not in toKeep and lines[index][3] == '0':
            toKeep.append(lines[index])
            break

# Deleting all files of the selected 90% of rows
for i, line in enumerate(lines):
    if i == 0:  # Omit the header row
        continue
    if lines[i][3] != '0':  # Keep rows that don't have a steering value of 0
        toKeep.append(lines[i])
    if line not in toKeep:
        print("Deleting: {}".format(line))
        for i in range(3):
            remove(line[i])

with open('data/driving_log.csv', 'w', newline='') as csvfile:
    writer = csv.writer(csvfile)
    writer.writerows([lines[0]])  # Put the header back in
    writer.writerows(toKeep)

我意识到这不是最优雅的解决方案。我不熟悉numpy,现在没有时间学习它,但这应该可以用。

您搜索过如何在python中生成随机数和删除文件吗。是的,我需要导入random并使用os.remove()删除该文件。但是,我在两个地方感到困惑,从csv文件中删除一行,并随机删除90%的指导值等于0的文件。您能以文本格式发布csv文件的一部分吗?最好使用逗号作为分隔符。此外,您的代码不完整。很多未定义的变量。IMG/center_2016_12_01_13_30_48_287.jpg,IMG/left_2016_12_01_13_30_48_287.jpg,IMG/right_2016_12_01_13_30_48_287.jpg,0,0,22.14829。嘿,谢谢。但我看不到转向角需要为0的情况。另外,我还想删除相应的文件。我想删除IMG文件夹中的
center\u 2016\u 12\u 01\u 13\u 30\u 48\u 287.jpg
。你能帮我做这两件事吗?这行
如果行[index]不在toKeep和行[index][3]='0':
说明如果我们还没有将行添加到要保留的行列表中,并且如果转向柱等于0,那么…这些行:
用于范围(3)中的i:
删除(行[i])
将删除该特定行的3个文件中的每一个。