'How to find a specific word in CSV column and write its position into the next column using Python
How to find a specific word in a column and write its position in next column in Python.
For example I have a CSV File
And I want to find a "(correct)" word and then put its position in next column, and continue to loop through whole file like this.
In this example, banana has word "(correct)" and is in 3rd in column so G is edited as 3.
And the same goat has the word "(correct)" so we added 4 in G column
Also replace the "(correct)" with empty string after each loop
Solution 1:[1]
Without more sample data to test, and if all you want is a really quick solution to get you started... see below.
with open(csvfile) as csvf: # open csv file
lines = csvf.read().split("\n") # split contents into lines
for i, line in enumerate(lines):
row = line.split(",") # split lines into columns
for j, col in enumerate(row):
if "(correct)" in col: # check if keyword in column
row.append(str(j)) # append the row to last column
lines[i] = ','.join(row)
with open(csvfile, 'wt') as csvfw:
csvfw.write('\n'.join(lines)) # write lines back to file.
There is also the csv module in the python stdlib you may want to check out.
https://docs.python.org/3/library/csv.html#module-csv
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | alexpdev |

