Python 在文本文件中搜索字符串并在与此字符串相同的行上写入
我正在写一个简单的算术测验。我的目标是将参与者的分数和姓名存储到一个文本文件中,但是如果他们之前已经参加了测试,那么分数应该附加到他们姓名所在的同一行。这是我的代码:Python 在文本文件中搜索字符串并在与此字符串相同的行上写入,python,file-handling,Python,File Handling,我正在写一个简单的算术测验。我的目标是将参与者的分数和姓名存储到一个文本文件中,但是如果他们之前已经参加了测试,那么分数应该附加到他们姓名所在的同一行。这是我的代码: 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
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()
但是,没有证据表明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)
或者将fileinput.input与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())
使用dict和pickle,您就可以轻松地查找名称also@PadraicCunningham我试图避免酸洗,因为这是学校作业,我需要保持简单当以写模式第二次打开时,不会覆盖所有现有数据吗?不担心,我也更喜欢第一种解决方案,我刚才说我会给你看一个备选方案。有可能在同一行上有多个分数,因为解决方案1会用最新的分数更新它,还是会?我不确定