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

时间:2016-01-21 10:32:03

标签: python python-3.x text-files

我有一个程序计算得分'LevelScore',我想打开UserFile'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...

3 个答案:

答案 0 :(得分:2)

这应该让你开始。

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

不幸的是,无法在文件中间更改某些内容。因此,您必须解析所有内容,进行修改然后再次编写。

答案 1 :(得分:1)

这是我和Luke合作提出的解决方案:

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

if LevelScore > UserLevelScore:
    UserFileWR = open("UserScoreFile.txt","w+")
    UserFileLines[lev] = "T " + str(LevelScore) + "\n"
    UserFileRW.writelines(UserFileLines)
    UserFileRW.close()

感谢Jotto和Tim Pietzcker的贡献。

答案 2 :(得分:0)

使用fileinput module,您可以这样做:

import fileinput
with fileinput.input(files=["test.txt"], inplace=True) as f:
    for line in f:
        if fileinput.lineno() == lev+1:     # line numbers start at 1, not 0
            UserLevelScore = int(line[2:5]) # assuming LevelScore is an int
            if LevelScore > UserLevelScore:
                line = "{}{:0>3}".format(line[:2], LevelScore)
                # right-justify LevelScore with leading zeroes
        print(line, end="") # Output is redirected to the current line of the file