python - 想要用Python中的新字符覆盖文本文件中特定行上的特定字符

标签 python python-3.x text-files

我有一个计算分数“LevelScore”的程序,我想打开用户文件“UserScoreFile”并检查文件中保存的当前用户分数,如果 LevelScore > CurrentScore 会覆盖代表该级别分数的先前字符将文本文件添加到 LevelScore。

文本文件中的每一行代表0-7的级别,每行格式为“T 000”,T代表级别是否解锁,000代表当前分数(分数可以是0-100)“lev "是 0-7 之间的变量,指示用户处于哪个级别。

UserFileR = open("UserScoreFile.txt","r")
    UserFileLines = UserFileR.readlines()
    UserLevelLine = UserFileLines[lev]
    UserLevelScore = UserLevelLine[2:5]

 if LevelScore > UserLevelScore:
    UserFileWR = open("UserScoreFile.txt","r+")
    #This is where i dont know what to do...

最佳答案

这应该可以帮助您入门。

UserFileRW = open("UserScoreFile.txt","r+")
UserFileLines = UserFileR.readlines()
UserLevelLine = UserFileLines[lev]
UserLevelScore = int(UserLevelLine[2:5])

if int(LevelScore) > UserLevelScore:
    UserFileRW.truncate()
    UserFileLines[lev] = "some tex" + str(LevelScore)  # there is something before score, but I don't know what
    UserFileRW.write(''.join(UserFileLines))
    UserFileRW.close()

不幸的是,这不可能更改文件中间的某些内容。所以你必须解析所有内容,进行修改,然后重新编写。

关于python - 想要用Python中的新字符覆盖文本文件中特定行上的特定字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34921233/

相关文章:

python - 如何在 PyQt 中指定主题?

C# - 使用正则表达式将数据排序到/从列表框

c# - 如何在另一个文本文件中搜索文本文件中的行

python - 我写了一个 pygame 程序,但是当我尝试使用 py2exe 时,我在 dist 中没有得到 exe

python - 无法使用 Puppet 设置 Python 3 的安装目录

python - MySQL/Python -- 提交的更改未出现在循环中

python - 我应该如何使用 Optional 类型提示?

dart - 如何在 Flutter 中读写文本文件

python - 与 python 中的 np.nan 进行标量比较

python-3.x - 如何在 python 中更改我的 Slack 机器人图标?