简体   繁体   English

在文本文件中搜索字符串并与此字符串在同一行上编写

[英]Searching for string in text file and writing on the same line as this string

I am writing a simple arithmetic quiz. 我正在写一个简单的算术测验。 My aim is to store the score and name of the participants to a text file, however if they have already taken the test before then the score should be appended to the same line as their name is on. 我的目标是将参与者的分数和姓名存储到文本文件中,但是如果参与者之前已经参加过考试,则应将分数附加到参与者姓名所在的同一行。 This is my code: 这是我的代码:

src = open("Class {} data.txt".format(classNo),"a+",)
for line in src:
    if surname.lower() in line:
        print("yes")
        # score should be written on same line as the surname is in the txt fileS
        src.write(score)
    else:
        print("nope")

src.close()    

However there is no evidence that python has executed the if statement as neither "yes", nor "nope" has been printed and the text file remains the same. 但是,没有证据表明python已执行if语句,因为既没有打印“ yes”,也没有打印“ nope”,并且文本文件保持不变。

with open("Class {} data.txt".format(classNo),"a+",) as src:
    lines = src.readlines() # all lines are stored here
    for ind,line in enumerate(lines):
        if surname.lower() in line:
            print("yes")
            # score should be written on same line as the surname is in the txt fileS
            lines[ind] = "{} {}\n".format(line.rstrip(), score) # add first or new scores 
        else:
            print("nope")
    with open("Class {} data.txt".format(classNo),"w",) as src: # reopen and write updated lines
        src.writelines(lines)

Or use fileinput.input with inplace=True : 或将fileinput.input与inplace inplace=True

import fileinput
for line in fileinput.input("Class {} data.txt".format(classNo),inplace=True):
    if surname.lower() in line:
        print("{} {}".format(line.rstrip(), score))
    else:
        print(line.rstrip())

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

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