I want to edit a row in csv in python

Question:

I’m writing a python code handling csv files and I want to edit a row. The best way ive figured out is by deleting the row and adding the new edited row at the end. Im able to do everything other than deleting the row.

Here I am reading and creating a new edited row:

data = []

with open('followers.csv', 'r') as followersData:
    reader = csv.DictReader(followersData)

    for i in reader:
        if i['username'] == 'user1':
            data.append(i['username'])
            data.append(i['followers'])

    followers = data[1].split(sep='-')
    followers.append('user6')
    data[1] = '-'.join(followers)

After this I tried a few things but I can’t delete the existing row or overwrite it. Any help would be appreciated.

This is the csv file and I want to edit the first row with information:

username,followers
user1,user2-user3-user4
user2,user1-user3-user4
user3,user1-user2-user4
Asked By: Syed Abdullah

||

Answers:

This snippet of code will add one follower to the person you specify

user_to_add = "user6"     # the new follower
user_to_add_to = "user1"   # the user we are adding the follower to

Entire code block:

import csv

# START:

# username,followers
# user1,user2-user3-user4
# user2,user1-user3-user4
# user3,user1-user2-user4

# END:

# username,followers
# user1,user2-user3-user4-user6
# user2,user1-user3-user4
# user3,user1-user2-user4

data = []

# "i only want to add it to a single row, user1 in this case"
# this section reads in data
with open('followers.csv', 'r') as followersData:
    reader = csv.DictReader(followersData)

    for i in reader:
        data.append(i)
    

user_to_add = "user6"     # the new follower
user_to_add_to = "user1"   # the user we are adding the follower to

# update the file
with open('followers.csv', 'w') as f:
    
    f.write("username,followersn")  # add top line
    
    for row in data:
        
        if row["username"] == user_to_add_to:  # add new follower to the row
            old_followers = row["followers"]
            row["followers"] = f"{old_followers}-{user_to_add}"
        
        user = row["username"]
        followers = row["followers"]
        f.write(f"{user},{followers}n")  # write row to file
Answered By: Mitchnoff
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.