Home > Blockchain >  Edit a specific item in a CSV File
Edit a specific item in a CSV File

Time:12-11

My goal is letting the user edit their user data from a csv file. The content of the csv file ("bingus.csv") looks something like this:

username,fullname,age,gender,stutter,speed
annab,Anna Burr,15,f,y,f
tim1,Timothy Mayers,18,m,n,s

What I've managed to do is write a code that will let the user put in a new fullname and the programm will then rewrite all lines to have that new fullname:

import csv
import shutil
from tempfile import NamedTemporaryFile

filename = "bingus.csv"
temp_file = NamedTemporaryFile(delete=False)

fullname= input("Your full name: ")
            with open(filename, "rb") as csvfile, temp_file:
                reader = csv.DictReader(csvfile)
                filename = ['username', 'fullname', 'age', 'gender', 'stutter', 'speed']
                writer = csv.DictWriter(temp_file, fieldnames=fieldnames)
                writer.writheader()
                for row in reader:

                    writer.writerow({
                        "username": row["username"],
                        "fullname": fullname,
                        "age": row["age"],
                        "stutter": row["stutter"],
                        "speed": row["speed"]
                    })
            shutil.move(temp_file, filename)

The plan is to only edit the row that includes the currently logged in username specifically. There are a lot of posts about editing specific rows/columns of a csv file, yet none of them have seemed to be able to help me and I'm becoming quite desperate. Could anyone help me?

CodePudding user response:

At no point do you actually define a variable containing the "logged in username" as you call it. Assuming this will be defined through another input then all you need to is add a simple condition that will only modify the fullname if the username matches. Your code then becomes :

import csv
import shutil
from tempfile import NamedTemporaryFile

filename = "bingus.csv"
temp_file = NamedTemporaryFile(delete=False)

fullname = input("Your full name : ")
username = input("Your username  : ")
with open(filename, "rb") as csvfile, temp_file:
    reader = csv.DictReader(csvfile)
    filename = ['username', 'fullname', 'age', 'gender', 'stutter', 'speed']
    writer = csv.DictWriter(temp_file, fieldnames=fieldnames)
    writer.writheader()
    for row in reader:
        writer.writerow({
            "username": row["username"],
            "fullname": fullname if row["username"] == username else row["fullname"],
            "age": row["age"],
            "stutter": row["stutter"],
            "speed": row["speed"],
        })
    shutil.move(temp_file, filename)

  • Related