简体   繁体   中英

How do I filter all lines out of a csv that comply a specific rule and write them to a new csv in Python?

I have this CSV with lots of data, it's basically a list of pictures, labels and coordinates like this:

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

Now I cut out the NewID300004, this is the id of the picture. I want all lines with a 3 just after NewId to go to a file called clip3.csv I try this:

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]])

Now this does indeed write it to a csv with that name, but only 1 line of it... Maybe it overwrites the first line every time? Maybe not, I don't know. I know this might seem a silly problem but if someone could give me a nudge in the right direction I would be very gratefull. I'm very new to Python and still learning more every day.

Ofcourse as soon as I posted the question I came up with the answer. I'll post it here for good measure. The only change I had to make was in the line:

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

I changed it too append-mode (which sounds really cool too!)

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

so from 'w' to 'a+'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM