我试图将字符串附加到.tmp/uploads/
函数返回的列表中。
readlines()
否则: 打开(文件," w")为f: 换行: f.write(线)
当我测试它时,如果名称已经被转储到文件中,它就可以了。 但是,当我第二次运行模块时,会删除附加到列表中的数字,而是替换为新数字。
E.G。
如果我输入名称Gerald Tim并且程序在文件中找到该名称, 我第一次运行它时会将数字添加到名称中,但是第二次运行它会删除另一个数字,用新输入替换它 号。
我希望程序不要删除最后一个数字输入。
答案 0 :(得分:0)
我认为你不应该修改你正在迭代的列表。尝试迭代副本并修改原始文件。此外,您实际上并没有将新行写回文件。试试这个:
number = str(int(input("Number:")))
input_name = ((input("Lastname:") + (input("Firstname:")))
file = "TXT.txt"
# Open file with default mode for reading
f = open(file)
lines = f.readlines()
f.close() # close the file sooner rather than later.
# Loop for each line in the file
for line in list(lines): # <-- Create a copy to iterate over
# The name is the values indexed from 0 (first character) to -4 (fourth to last character)
name = line[0:-4]
# Check if name has been appended before
if name == input_name:
# If value of name is input_name, concentrate the number onto the line
found = True
print("\nYour name has been found in the file.\n")
new_line = line[:-1] + "," + number + "\n"
lines.remove(line)
lines.append(new_line)
# Break the loop
break
# Otherwise, continue the loop
else:
found = False
# Overwrite the file with the updated data.
with open(file, 'w') as myfile:
myfile.writelines(lines)
readlines
方法只提供从文件中读取的行的列表 - 修改它不会修改文件。获得修改后的列表后,覆盖该文件。现在这个号码应该在第二次运行时出现。
希望有所帮助。
答案 1 :(得分:0)
有点简洁易读(pythonic)。这将根据您的条件查找名称,并将结果附加到上面脚本中指定的数组中。
number = str(int(input("Number:")))
input_name = ((input("Lastname:") + (input("Firstname:")))
file = "TXT.txt"
# initialize result array
res_array = []
# Open file with default mode for reading
with open(file, 'r') as f:
for line in f.readlines():
if input_name == line[0:-4]:
print("\nYour name has been found in the file")
res_array.append("{0},{1}".format(line[:-1], number))
break
else:
res_array.append(line)
# print out the resulting array
print(res_array)
如果您需要输出到另一个文件,那么:
number = str(int(input(“Number:”))) input_name =((input(“Lastname:”)+(input(“Firstname:”)))
file = "TXT.txt"
# output file
outfile = "outTXT.txt"
# Open file with default mode for reading
with open(file, 'r') as f:
with open(outfile, 'w') as fo:
for line in f.readlines():
if input_name == line[0:-4]:
print("\nYour name has been found in the file")
fo.write("{0},{1}\n".format(line[:-1], number))
break
else:
fo.write("{0}\n".format(line))
通过 with 关键字,文件将在退出特定缩进后立即关闭。