Python - Replacing a specific value in a CSV file while keeping the rest

266 views Asked by At

So I have a CSV file that looks something like this:

Username,Password,Name,DOB,Fav Artist,Fav Genre
Den1994,Denis1994,Denis,01/02/1994,Eminem,Pop
Joh1997,John1997,John,03/04/1997,Daft Punk,House

What I need to be able to do is let the user edit and change their Fav Artist and Fav Genre so that their new values are saved to the file in place of the old ones. I'm not the very advanced when it comes to CSV so I'm not sure where to begin with it, therefore any help and pointers will be greatly appreciated.

Thanks guys.

EDIT:

Adding the code I have so far so it doesn't seem like I'm just trying to get some easy way out of this, generally not sure what to do after this bit:

def editProfile():
    username = globalUsername
    file = open("users.csv", "r")
    for line in file:
        field = line.split(",")
        storedUsername = field[0]
        favArtist = field[4]
        favGenre = field[5]
        if username == storedUsername:
            print("Your current favourite artist is:", favArtist,"\n" + 
                  "Your current favourite genre is:",favGenre,"\n")
            wantNewFavArtist = input("If you want to change your favourite artist type in Y, if not N: ")
            wantNewFavGenre = input("If you want to change your favourite genre type in Y, if not N: ")
            if wantNewFavArtist == "Y":
                newFavArtist = input("Type in your new favourite artist: ")
            if wantNewFavGenre == "Y":
                newFavGenre = input("Type in your new favourite genre: ")
3

There are 3 answers

0
Stefan Falk On BEST ANSWER

This is how it would look like using pandas

import pandas as pd
from io import StringIO

# Things you'll get from a user
globalUsername = "Den1994"
field = 'Fav Artist'
new_value = 'Linkin Park'

# Things you'll probably get from a data file
data = """
         Username,Password,Name,DOB,Fav Artist,Fav Genre
         Den1994,Denis1994,Denis,01/02/1994,Eminem,Pop
         Joh1997,John1997,John,03/04/1997,Daft Punk,House
       """

# Load your data (e.g. from a CSV file)
df = pd.read_csv(StringIO(data)).set_index('Username')

print(df)

# Now change something
df.loc[globalUsername][field] = new_value

print(df)

Here df.loc[] allows you to access a row by the index. In this case Username is set as index. Then, [field] selects the column in that row.

Also, consider this:

df.loc[globalUsername][['Fav Artist', 'Fav Genre']] = 'Linkin Park', 'Nu Metal'

In case you have a my-data.csv file you can load it with:

df = pd.read_csv('my-data.csv') 

The code above will return

           Password   Name         DOB Fav Artist Fav Genre
Username                                                   
Den1994   Denis1994  Denis  01/02/1994     Eminem       Pop
Joh1997    John1997   John  03/04/1997  Daft Punk     House

and

           Password   Name         DOB   Fav Artist Fav Genre
Username                                                     
Den1994   Denis1994  Denis  01/02/1994  Linkin Park       Pop
Joh1997    John1997   John  03/04/1997    Daft Punk     House
0
bmello On

Try this

import pandas as pd 

data = pd.read_csv("old_file.csv")
data.loc[data.Username=='Den1994',['Fav Artist','Fav Genre']] = ['Beyonce','Hard rock']
data.to_csv('new_file.csv',index=False)
0
ahed87 On

python has a built-in module dealing with csv, there are examples in the docs that will guide you right.

One way to do is to use the csv module to get the file you have into a list of lists, then you can edit the individual lists (rows) and just rewrite to disk what you have in memory.

Good luck.

PS: in the code that you have posted there is no assignment to the "csv in memory" based on the user-input

a minimal example without the file handling could be:

fake = 'abcdefghijkl'
csv = [list(fake[i:i+3]) for i in range(0, len(fake), 3)]
print(csv)

for row in csv:
    if row[0] == 'd':
        row[0] = 'changed'

print(csv)

the file handling is easy to get from the docs, and pandas dependance is avoided if that is on the wishlist