替换python中文本文件的一行

2024-09-27 07:31:57 发布

您现在位置:Python中文网/ 问答频道 /正文

我对Python还很陌生,我正在尝试使用不和谐.py这个想法是你可以赚取硬币,显示在你的个人资料。问题是我需要将配置文件存储在一个单独的文件中,所以看起来像这样

userID1,10
userID2,20
userID3,30

预期产量:

userID1,10
userID2,120
userID3,30

基本上是“一个用户的不和谐id,硬币的数量”,我试图取代行,但与不同数量的硬币,我不知道如何做到这一点,而不做另一个文件。你知道吗

我现在只有这些了。你知道吗

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是一个用户的ID,因此每个用户的ID不同,Points是我要添加的点数


Tags: 文件用户inpyinfoid数量line
1条回答
网友
1楼 · 发布于 2024-09-27 07:31:57

我建议您使用以下解决方案,并在代码中添加注释进行解释:

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)  

相关问题 更多 >

    热门问题