如何在python中覆盖部分文本文件

2024-10-01 17:30:53 发布

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

我有一个文本文件,其中包含用户用户名,密码和最高分,但我想覆盖他们的高分时,获得高分。但是,我只想覆盖那个特定的值,而不想覆盖其他值。你知道吗

这是我的文本文件(名为'用户.txt'):

david 1234abc 34 hannah 5678defg 12 conor 4d3c2b1a 21

例如,如果“hannah”得到了15分,我想把12分改成15分

下面是我在python中尝试的内容:

# splitting the file
file = open("users.txt","r")
read = file.read()
users = read.split()
file.close()
# finding indexs for username, password and score
usernamePosition1 = users.index(user)
passwordPosition1 = usernamePosition1 + 1
scorePosition1 = passwordPosition1 + 1

file = open("users.txt","a")
# setting previous high score to an integer
player1OldScore = int(users[scorePosition1])


if player1Score > player1OldScore:
  # setting in back to a str for text file
  player1ScoreStr = str(player1Score)
  # from here on i dont really know what i was doing
  users.insert([scorePosition1],player1ScoreStr)
  file.write(users)
  print(player2 + "\n \nAchieved a new high score")
else:
  print("\n \n" + player1 + " , you didn't achieve a new high score")

抱歉代码有点乱,不过我希望有人能帮忙。 提前谢谢, 代码向导


Tags: 用户txtforreadopenusersfilescore
3条回答

您的想法是正确的(请注意,我认为您的代码只适用于1个用户,但我会让您知道如何扩展它),但是如果不编写整个文件,就无法更改文件。你知道吗

因此,我建议如下:

...
file = open("users.txt","w") # change this from 'a' to 'w' to overwrite
player1OldScore = int(users[scorePosition1])

if player1Score > player1OldScore:
  users[scorePosition1] = str(player1Score) # change the score
  file.write(" ".join(users)) # write a string with spaces between elements
  print(player2 + "\n \nAchieved a new high score")

...

您需要找到并替换字符串。这意味着您需要格式化用户.txt文件的方式,您可以简单地替换用户数据。如果您将每个用户及其数据放在单独的行上,这应该相当容易:

import string
s = open("users.txt","r+")
for line in s.readlines():
   print line
   string.replace(line, 'hannah 5678defg 12','hannah gfed8765 21')
   print line
s.close()

你的文本文件格式很脆弱。如果David使用"hannah"作为密码,那么当Hannah尝试更新她的分数时,它将查找她的名字作为第二个字段,而不是查找她的分数(第六个字段),并尝试使用第四个字段(她的名字)作为她的分数!任何人在他们的密码中使用空格也会引起问题,尽管一个偷偷摸摸的人可以使用“abcd 1000000”作为他们的初始密码,并将他们的初始分数设定为一百万。你知道吗

这些问题可以通过以下方法解决:

  • 每个用户使用一行,或
  • 仅在每3个字段的第一个字段中搜索用户名

以及

  • 不允许在密码中使用空格,或
  • 密码编码/加密

在任何情况下,都必须读入并存储现有数据,然后将整个数据集写入文件。原因是数据没有存储在固定宽度的字段中。如果分数从99变为100,则需要将文件的所有后续字符向前移动一个字符,这不是对文件所做的修改,而不实际读取和重写整个文件。你知道吗

相关问题 更多 >

    热门问题