0

I'm pretty new to Python and I'm trying to make a discord bot using discord.py and the idea is that you can earn coins that are showed on your profile. The problem is that I need to store the profiles in a single file so it looks like this

userID1,10
userID2,20
userID3,30

Expected output:

userID1,10
userID2,120
userID3,30

Basically "discord id of a user,amount of coins" and I'm trying to replace the line but with a different amount of coins and I have no idea on how to do this without making another file.

This is all I have right now.

def addExp(userID,Points):
    with open(fname) as f:
        for line in f:
            if userID in line:
                info = line.split(',')
                newPoints= int(info[1]) + Points

UserID is the ID of an user so it's different for each user and Points is the amount of points I want to add

Nourios
  • 41
  • 4
  • Could you include an example of your expected output? I think this will help give people the complete picture. also, the syntax of your code should be `if "UserID" in line:` – d_kennetz Aug 21 '18 at 15:08
  • As far as I understand you want to use the file as a database. How big is the file supposed to be? If not so huge, I think the best way is to keep all the data into a variable and "smartly" backup the value into the file. If the file is huge, you should have a look at portable databases like SQLite. They work with the file system in an efficient way using descriptors. – Fomalhaut Aug 21 '18 at 15:25

1 Answers1

0

I suggest you the following solution, with comments in the code to explain:

def addExp(UserID, Points):
    # Open the file and read the full content
    with open(fname, 'r') as f:
        lines = f.readlines()
    # Iterate over each line and replace the number of coins
    for i in range(len(lines)):
        if UserID in lines[i]:
            info = lines[i].split(',')
            info[1] = str(int(info[1]) + Points)
            lines[i] = ",".join(info) + '\n'
    # Overwrite the file with the updated content
    with open(fname, 'w') as f: 
        f.writelines(lines)


fname = 'file.txt'
addExp("userID2", 100)  
Laurent H.
  • 6,316
  • 1
  • 18
  • 40