0

I have a 14000 lines with two fields each csv file and am trying to remove some rows that occur randomly. I intend to keep everything besides the rows containing any of the following: "Station Name", "Location Code", "Parameter".

I am trying to open the file containing the data together with a new empty csv file that will be used to write the new data into. I am trying to loop through each line of the csv file and write into the new file only the lines which do not have the first field equal to any of the mentioned values.

I am trying the following but I end up with an exact copy of the initial data.

import csv
with open('combined_csv.csv', newline='') as inp, open('edited.csv', 'w', newline='') as out:
    writer = csv.writer(out)

    for row in csv.reader(inp):
        if row[0] != "Station Name" and "Location Code" and "Parameter":
            writer.writerow(row)

Any help is appreciated

pietre
  • 33
  • 7

1 Answers1

0

Your if statement won't work as you expected. If you want to check string to be not equal with several strings I recommend you to do like this:

if row[0] not in ("Station Name", "Location Code", "Parameter"):
    writer.writerow(row)

Upd.

Your version works well but why is mine not working?

if row[0] != "Station Name" and "Location Code" and "Parameter":

You're trying to check row[0] to be not equal with "Station Name" and "Location Code" and "Parameter".

Let's print it:

>>>"Station Name" and "Location Code" and "Parameter"
'Parameter'

Why? Let's do some experiments:

>>>"Station Name" and "Location Code" and "Test"
'Test'

>>>False and "Station Name" and "Location Code" and "Test"
False

>>>"" and "Station Name" and "Location Code" and "Test"
''

>>>"Station Name" and "Location Code" and "" and "Test"
''

Still have questions? Okay:

>>bool("Non-empty string")
True

>>>bool("")
False

So, your code is equivalent of

if row[0] != "Parameter":

How to write it properly.

if row[0] != "Station Name" and row[0] != "Location Code" and row[0] != "Parameter":
Olvin Roght
  • 7,677
  • 2
  • 16
  • 35