I have a csv file where I have some names and the date from when students have passed the exam. if they did not pass the exam the date will be empty. how could I filter out the empty field so I only have a list with people that have passed the test?
Here is the code that I have. the row[0] is the names of the student and row[12] is the date they have passed it.
with open("MYCSV_FILE", 'r') as read_obj:
csv_dict_reader = csv.reader(read_obj, delimiter=';')
for row in csv_dict_reader:
if row[12]:
with open('fed_results\Behaalde_studenten.csv', 'a') as f_object:
# Pass the CSV file object to the writer() function
writer_object = csv.writer(f_object)
# Result - a writer object
# Pass the data in the list as an argument into the writerow() function
writer_object.writerow(row[0])
# Close the file object
f_object.close()
CodePudding user response:
row[12]
can be checked for an empty result like this:
if row[12]:
# do something #
So your code can check for non-empty rows by:
with open("MYCSV_FILE", 'r') as read_obj:
csv_dict_reader = csv.reader(read_obj, delimiter=';')
for row in csv_dict_reader:
if row[12]:
print(row[0], row[12])
Or you can consider an if/else statement:
with open("MYCSV_FILE", 'r') as read_obj:
csv_dict_reader = csv.reader(read_obj, delimiter=';')
for row in csv_dict_reader:
if row[12]:
print(row[0], row[12])
else:
# what to do if it isn't there #
This all assumes that each row is delimited by a semicolon even when empty values are given, such that:
a;b;c;d;e;f;g;h;i;j;k;l
1;2;3;4;5;6;7;8;9;10;11;