我有这样的文本文件:
tw004:Galaxy S5:Samsung:Mobilni telefon:7
tw002:Galaxy S6:Samsung:Mobilni telefon:7
tw001:Huawei P8:Huawei:Mobilni telefon:3
tw003:Huawei P9:Huawei:Mobilni telefon:9
(其中tw001到tw004是一些设备的代码,行的最后一部分是数量7,7,3,9)
代码如下:
def export_devices():
code = input("Enter device code: ")
amount = int(input("How many devices you export: "))
with open("uredjaji.txt", "r+") as f:
current_position = 0
line = f.readline()
while line:
if line[:len(code) + 1] == code + ":":
remaining_content = f.read()
f.seek(current_position)
f.truncate()
line = line.rstrip()
amount_index = line.rfind(":") - 1
current_amount = int(line[amount_index:])
line = line[:amount_index] + str(current_amount + amount) + "\n"
f.write(line)
f.write(remaining_content)
return
current_position = f.tell()
line = f.readline()
print("Invalid device code: {}".format(code))
export_devices()
现在我想打印错误,如果输入量大于文件中的当前量。这不完全是我的代码,所以我不能解决,但我尝试了很多方法与一些如果语句,但仍然不工作。你知道吗
啊,那代码看起来很眼熟。。。无论如何,只需在对文件进行破坏性更改之前移动
current_amount
解析,并在解析后添加检查:你也应该试着理解你正在使用的代码。我在回答你之前的问题时写了大量的评论,这样你就可以理解它的作用,如果有什么不清楚的地方,你应该问一下,而不是盲目地复制粘贴代码。你知道吗
相关问题 更多 >
编程相关推荐