Editing data in a CSV file using Python

31 Views Asked by At

I am writing data to a notepad (.txt) file in Python. Entities are separated with commas (','). The file is called 'Database2.txt'.

The variable 'yearlynew' contains a float value that will replace a piece of existing data. I have tried various methods of writing said data to the file but cannot get it to work.

This is the code that I have so far:

g = open('Database2.txt', 'r')
for line in g:
    CurrentLine = line.split(',')
    if CurrentLine[0] == account:
        g = open('Database2.txt', 'a')
        #CurrentLine[3] = yearlynew
        #g(CurrentLine[3]).write(yearlynew)
        #CurrentLine[3].write(yearlynew)

Anything with a '#' before it indicates a failed method that I have tried. If anybody has any suggestions on how to do this I would be very grateful.

I should note that CurrentLine[0] identifies usernames (which are in the first column of the file) so that whichever user is logged in can edit their data and their data only. 'account' holds the username of the user that is currently logged in, and allows the program to trace through the file to find the user's statistics. User data such as names and passwords are stored in a separate file and are not needed for this function.

This is the contents of the file:

Ellie121,0.16,5,60,

Sam232,0.2,6,72,

Heather343,0.1,3,36,

Connor454,0.35,10.5,126,

Ryan565,0.15,4.5,54,

Matthew676,0.22,6.6,79.2,

1

There are 1 best solutions below

2
On

I don’t think that you can just insert text into a file. I think you will have to write the new data to a different file and then rename it. This is how I would go about it :

import os

account = 'Sam232'
yearlynew = '3.14159'

temp = open ('temporary_file', 'w')
g = open ('Database2.txt', 'r')
for line in g :
    CurrentLine = line.split (',')
    if CurrentLine [0] == account :
        CurrentLine [1] = yearlynew
    OutputLine = ','.join (CurrentLine)
    temp.write (OutputLine)
g.close ()
temp.close ()

os.remove ('Database2.txt')
os.rename ('temporary_file', 'Database2.txt')