简体   繁体   English

如何在 Python 中覆盖文本文件的一部分?

[英]How do I overwrite part of a text file in Python?

I have a text file that contains users username, password and highest score, however I want to overwrite their high score when the achieve a high score.我有一个包含用户名、密码和最高分的文本文件,但是我想在达到高分时覆盖他们的高分。 However I only want to overwrite that specific value and no others.但是,我只想覆盖该特定值而不是其他值。

This is my text file (called 'users.txt') :这是我的文本文件(称为“users.txt”):

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

For example, if 'hannah' gets a new score of 15, I want to change 12 to 15例如,如果 'hannah' 的新分数为 15,我想将 12 更改为 15

Here is what I've tried:这是我尝试过的:

# 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")

Your text file format is rather brittle.您的文本文件格式相当脆弱。 If David uses "hannah" as a password, then when Hannah tries to update her score, instead of locating her score (the sixth field), it will find her name as the second field and try using the fourth field (her name) as her score!如果 David 使用"hannah"作为密码,那么当 Hannah 尝试更新她的分数时,而不是定位她的分数(第六个字段),它会找到她的名字作为第二个字段并尝试使用第四个字段(她的名字)作为她的分数! Anyone using a space in their password would also cause problems, although a sneaky person could use “abcd 1000000” as their initial password and seed their initial score as one million.任何人在他们的密码中使用空格也会导致问题,尽管一个鬼鬼祟祟的人可以使用“abcd 1000000”作为他们的初始密码,并将他们的初始分数设为 100 万。

These problems can be fixed by:这些问题可以通过以下方式解决:

  • Using 1 line per user, or每个用户使用 1 条线路,或
  • Searching for user names only in the first of every 3 fields仅在每 3 个字段的第一个中搜索用户名

And

  • disallowing spaces in passwords, or禁止在密码中使用空格,或
  • coding/encrypting the passwords编码/加密密码

In any case, you must read in and store the existing data, and then write out the entire dataset to the file.在任何情况下,您都必须读入并存储现有数据,然后将整个数据集写出到文件中。 The reason is the data is not stored in fixed-width fields.原因是数据没有存储在固定宽度的字段中。 A score changing from 99 to 100 will require moving all subsequent characters of the file one character forward, which is not a modification you can make to the file without actually reading and rewriting it in it's entirety.分数从 99 更改为 100 将需要将文件的所有后续字符向前移动一个字符,这不是您可以在不实际完整读取和重写文件的情况下对文件进行的修改。

You are going to need to find and replace the strings.您将需要查找并替换字符串。 This means you will need to format the users.txt file in a way that you are able to simply replace the user data.这意味着您需要以一种能够简单地替换用户数据的方式来格式化 users.txt 文件。 If you have each user and their data on a seperate line this should be fairly easy:如果您将每个用户及其数据放在单独的行上,这应该很容易:

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()

You have the right idea (note that I your code will only work for 1 user, but I'll let you figure out how to extend it), but there is no way to change the file without writing the entire file.您的想法是正确的(请注意,我的代码仅适用于 1 个用户,但我会让您弄清楚如何扩展它),但是在不编写整个文件的情况下无法更改文件。

As such I recommend something like this:因此,我推荐这样的东西:

...
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")

...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM