我编写的代码创建了一个文本文件(如果它不存在),并要求您输入一个名称和一个年龄来记录人名和年龄。我想在我的代码中添加一个elif,以便我可以更新人们的年龄。
例如,如果一个文本文件名为Paul并且他们的年龄是46岁,当我被要求输入姓名时我输入了Paul,我希望它只是要求更新年龄。
这是我的尝试,根本不起作用。
代码:
SELECT hackers.*, challenges.a AS c_a, challenges.b AS c_b, etc
文字档案:
while True:
family=open("FamilyAges.txt",'a+')
familyR=open("FamilyAges.txt",'r')
line1= familyR.readlines(1)
name = input('Enter name of person : ')
if name == 'end':
break
elif name == line1:
print('test')
else:
age = input('Enter age of person : ')
family.write((name)+' '+(age)+'\n')
family.close()
答案 0 :(得分:1)
最好的解决方案是读取所有文件,使用dict将其保存在内存中,然后在每次添加名称时更新dict。
当你决定停止时(输入'结束')用dict中的新值覆盖文件
答案 1 :(得分:1)
以下内容解决了您发布的代码的直接问题,但是对于您所描述的目标,您应该考虑:此代码仅检查文件的第一行,但您要检查名称是否在文件中的任何位置。
readlines(1)
返回一个包含一个元素的列表(第一行)。所以你需要的是:
while True:
family=open("FamilyAges.txt",'a+')
familyR=open("FamilyAges.txt",'r')
line1= familyR.readlines(1)
name = input('Enter name of person : ')
if name == 'end':
break
elif name in line1[0]:
print('test')
else:
age = input('Enter age of person : ')
family.write((name)+' '+(age)+'\n')
family.close()
请注意line1[0]
和name in line1[0]
(您需要这个,因为您的行不仅包含名称,还包含其他文字)。
答案 2 :(得分:1)
比乔的解决方案长一点,但我更喜欢功能。我没有更正你的代码,因为缺少某些部分 - 重写似乎是一个更好的选择,保持你使用的东西。
在gianluca回答“做什么”后,我为你实现了这个例子。
我使用with open(...) as f:
代替您的文件读取类型,因为它在离开以下块时会自动关闭/刷新/处理文件句柄。它是推荐使用文件的方式。 Dictionaries是一种快速键/值访问的数据结构,更适合您的问题,然后是简单的字符串。
将功能性分解为函数是范围有限且易于理解有助于保持代码更清晰。
def readFile(fn):
"""Read the file given as by filename fn.
Expected format:
one key:value per line, key being a name, value a string as age.
Returns a dictionary of the parsed contents key:value if no
errors occure. Returs False on IOError or FileNotFoundError"""
try:
with open(fn,"r") as f:
lines = f.read().split("\n") # read all, split at linebreaks
print(lines) # debugging output
rv = {}
for l in lines: # parse all lines
item =l.split(":",2) # split each
if item is not None and len(item)==2: # must be 2 parts
rv[item[0]] = item[1] # put key/valu into dict
return rv # return dict
except IOError:
return False # error - return false
except FileNotFoundError:
pass # error - no file, thats ok
return {} # no file found, return empty dict
def saveFile(fn,famil):
"""Saves a dictionary famil as filename fn.
Produced format:
one key:value per line, key being a name, value a string as age.
Overwrites existing file of same name with new contents."""
with open(fn,"w+") as f:
for i in famil: # for all keys in dict
f.write(i + ":" + famil[i] + "\n") # write file
fileName = "FamilyAges.txt" # consistent filename
family = readFile(fileName) # read it
if not isinstance(family,dict): # check if no error, if error, print msg & quit
print("Error reading file")
else: # we got a dict
print(family) # print it
gotInput = False # remember for later if we need to save new data
while True: # loop until name input is "end"
name = input('Enter name of person : ') # input name
if name == 'end': # check break condition
break
else:
age = input('Enter age of person : ') # input age as string, no validation
family[name] = age # store in dictionary
gotInput = True # this will "alter" existing
# ages for existing names
if (gotInput): # if input happened, save data to file
saveFile(fileName, family)
print(family) # print dict before end
答案 3 :(得分:0)
步骤:
try...except
或os.path
):
name: age
对人的字典name == "end"
突破循环"w"
)模式,因此将其消隐以下是这样的:
try:
d = {n:a for n, a in (l.split() for l in open("FamilyAges.txt").readlines())}
except FileNotFoundError:
d = {}
while True:
name = input("name: ")
if name == "end":
break #will escape loop here, so no need for `elif`s
age = input("age: ") #no need to convert to an integer as noo calculations
d[name] = age
with open("FamilyAges.txt", "w") as f:
for person in d.items():
f.write(" ".join(person) + "\n")
它有效!
$ python t.py
name: bob
age: 23
name: cat
age: 98
name: end
$ cat FamilyAges.txt
bob 23
cat 98
$ python t.py
name: bob
age: 67
name: fish
age: 10
name: end
$ cat FamilyAges.txt
bob 67
cat 98
fish 10