-1

I'd like to understand how to copy a row from a .csv file and paste it in another .csv. Specifically, I have a large number of .csv files with the same column format. For each of these files, I should search for a string in a column and, if I find it, I have to append the corresponding row in another csv file.

E.g. --> the string is "Bob"

file1.csv

| First Name | Last Name | Age |
| Bob        | Arnald    | 22  |
| Alice      | Halton    | 25  |
| Tom        | Jackson   | 26  |

file2.csv

| First Name | Last Name | Age |
| Max        | Phoenix   | 33  |
| Bob        | Niall     | 23  |
| Sean       | Roger     | 26  |

The output file would be
out.csv \

| First Name | Last Name | Age |
| Bob        | Arnald    | 22  |
| Bob        | Niall     | 23  |

I tried using csv library, but it's not clear how to isolate a single row and append it into another csv file.

Rabinzel
  • 7,757
  • 3
  • 10
  • 30
  • So, you want to create a new csv file only with common name from both csv files? – Nijat Mursali Nov 20 '22 at 18:25
  • I've just updated the question format (I think tables are more understandable now). My aim is to scan a specific column of each csv file (in the example, "First Name"). If I find a specific string in the column (in the example "Bob"), I want to copy the entire row corresponding the found string in the output csv file. – Pasquale Martorano Nov 20 '22 at 18:34
  • Does this answer your question? [How to copy rows from one CSV to another CSV file using Python](https://stackoverflow.com/questions/42807864/how-to-copy-rows-from-one-csv-to-another-csv-file-using-python) – Khaned Nov 20 '22 at 18:35

1 Answers1

0

Try this:

df1 = df1[df1['First Name'] == 'Bob']
df2 = df2[df2['First Name'] == 'Bob']
combined = pd.concat([df1, df2])

Note - pd.concat can be used on a list of any amount, therefore you can create a function to filter a df and iterate it over all your dfs, adding them to a list and then concatenating it.

CharlieBONS
  • 216
  • 7
  • df = pd.read_csv(filepath) Then when you get your dataframe of all combined rows new_df.to_csv(filepath/filename.csv) – CharlieBONS Nov 20 '22 at 18:28