I want to delete some rows from a CSV file by saving a new CSV after a validation process. I wrote the code below but it causes an error.
with open(path_to_read_csv_file, "r") as csv_file:
csv_reader = csv.DictReader(csv_file, delimiter=',')
for line in csv_reader:
# if validation(line[specific_column]):
try:
df = pd.DataFrame(line)
df.to_csv(path_to_save_csv_file)
except Exception as e:
print('Something Happend!')
print(e)
continue
Error:
Something Happend!
If using all scalar values, you must pass an index
I've also tried to add an index value by df = pd.DataFrame(line, index=[0])
, but it only stores the first line with an additional empty column at the beginning. How can solve this?
Another version with line
works but I can not reach a specific key value at each line:
inFile = open(path_to_read_csv_file, 'r')
outFile = open(path_to_save_csv_file, 'w')
for line in inFile:
try:
print('Analysing:', line)
# HERE, how can I get the specific column value? I used to use line[specific_column] in the last version
if validation(line[specific_column]):
outFile.write(line)
else:
continue
except Exception as e:
print('Something Happend!')
print(e)
continue
outFile.close()
inFile.close()