I have a file in the csv extension, which stores data about a person (first name, last name, phone number, date of birth). I need to change a certain position in it (for example, a name). I use pandas for this:

file = pd.read_csv('phonebook.csv', sep=',') name = input('Old name: ') surname = input('Surname: ') n_name = input('New name: ') reader = csv.reader(file_obj) for row in file: if name == row[0] and surname == row[1]: file.ix[0, row] = n_name file.to_csv('phonebook.csv', index=False) 

However, after calling the entire file, the changes are not saved. Tell me, please, how to make the changes saved?

1 answer 1

The beauty of Pandas in the absence of the need to use slow cycles:

 In [86]: df = pd.read_csv('c:/temp/phonebook.csv') In [87]: df Out[87]: firstname lastname 0 George Gershwin 1 George Benson 2 Ella Fitzgerald 3 Louis Armstrong In [88]: df.loc[(df['firstname']=='George') & (df['lastname']=='Gershwin'), 'firstname'] = 'Jacob' In [89]: df Out[89]: firstname lastname 0 Jacob Gershwin 1 George Benson 2 Ella Fitzgerald 3 Louis Armstrong In [90]: df.to_csv('c:/temp/phonebook.csv', index=False)