I've always been told not to update a file I'm reading/comparing.
When I'm doing something like comparing csv files like this I like to build a new list of file contents then check to see if the desired row or value is in the new list.
In your case I would;
- Create a new list containing the csv file values your looking at
- Define the string your looking for
- Check that the desired string is in the 25th element of the new list
- If it is append the 25th element with your desired string.
- Write a new updated csv file with the list you built/appended
This is what I came up with using a single file and a predefined keyword to find.
For your case, just add the file you want to get your keyword from, then set the keyword to be the [0] element in that list/file
Hope this helps
import csv
import os
csv_file = os.path.join(os.path.join(os.environ['USERPROFILE']),'Dir', 'file.csv')
updated_csv_file_path = os.path.join(os.path.join(os.environ['USERPROFILE']),'Dir', 'updated_file.csv')
with open(csv_file, 'r') as rawcsv, open(updated_csv_file_path, 'w', newline='') as csv_out_file:
reader = csv.reader(rawcsv)
writer = csv.writer(csv_out_file)
desired_file1_string = 'Greg'
update_string = 'OK'
file2_contents = []
# adds all of rows (lists) found in the csv file to a new list for us to update
for item in reader:
file2_contents.append(item)
print('Inital value of the 25th element: \n {}'.format(file2_contents[25]))
# if the desired string is in the 25th element of the list, appends ';OK' to the end of that list
if desired_file1_string in file2_contents[25]:
file2_contents[25].append(update_string)
print('Post append value of the 25th element: \n{}'.format(file2_contents[25]))
# writes a new csv file with the contents of file2_contents list
writer = csv.writer(csv_out_file)
for line in file2_contents:
writer.writerow(line)
The results
Inital value of the 25th element:
['Greg', 'Unruh', '', 'some_words', 'some more words']
Post append value of the 25th element:
['Greg', 'Unruh', '', 'some_words', 'some more words', 'OK']