Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

I want to edit a row in csv in python

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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,followers\n")  # 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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading