问题描述
这是我的代码:
classs = input("Class [1, 2 or 3] - ")
if classs =='1':
name = ).read():
print ("True")
break
else:
print ("False")
因此,基本上,我需要该程序在.txt文件中查找内容“名称”以及其附带的内容(同一行)
如果.txt文件中有“ Tom”(名称),而“ Tom”是“名称”,则程序将输出True。 由于在.txt文件中找到了该名称。
我的问题是我如何输出在名称下找到的内容,然后将允许我使用整数来输出平均分数。
1楼
我建议使用with构造,因为它可以为您处理关闭。 以下程序循环遍历文件中的所有行,以在读取的内容中查找名称
with open('1.txt', "r") as fp:
data = fp.readline()
while data != "":
if name in data:
print ("True")
break
else:
print ("False")
data = fp.readline()
2楼
它可能看起来像这样:
classs = input("Class [1, 2 or 3] - ")
if classs =='1':
name = input("What is your name? - ")
datafile = '1.txt'
found = False
# This is a better way to open the file, closes when done
with open(datafile, 'r') as f:
data = f.readlines()
for line in data:
if name in line:
print("True")
found = True
if found == False:
print("False")
希望这可以帮助!
3楼
首先,要读取文件的内容,请使用
content = ""
with open("yourfile.txt", "r") as f:
for s in f: content += s
您可以找到有关的更多信息。
因此,您将文件内容包含在变量内容中。 现在您的问题还不清楚。 第一部分很清楚,只写
if name in content:
...但是文件的格式是什么?
但...
如果要将用户分数保存在文件中的字典中,则最好使用pickle 。 所以首先您要导入泡菜:
import pickle
...而您拥有一本类似的字典
{“汤姆”:10,“帕斯卡”:12}
在可变分数中 ,将其保存为
pickle.dump(scores, open("myfile.p", "wb"))
并与阅读
scores = pickle.load(open("myfile.p", "rb"))
请参阅和 。