我有这样的txt文件:
tw004:Galaxy S5:Samsung:Mobilni telefon:5
tw002:Galaxy S6:Samsung:Mobilni telefon:1
tw001:Huawei P8:Huawei:Mobilni telefon:4
tw003:Huawei P9:Huawei:Mobilni telefon:3
(其中tw001到tw004是某些设备的代码,一行的最后一部分是金额5,1,4,3)
现在我正在尝试为具有指定代码的设备添加金额:
def add_devices():
device_file = open ('uredjaji.txt','r').readlines()
code = input("Enter device code: ")
for i in device_file:
device = i.strip("\n").split(":")
if code == device[0]:
device_file = open('uredjaji.txt', 'a')
amount = input("How many devices you are adding: ")
device[4] = int(device[4])
device[4] += int(amount)
device_file.writelines(str(device[4]))
device_file.close()
add_devices()
我的问题是指定设备的总和只是添加到txt文件的末尾。 如何解决? (例如,如果我输入tw004并且添加3总和8仅仅是tw003:华为P9:华为:Mobilni telefon:3 8 )
答案 0 :(得分:0)
由于您希望更新同一文件,因此您不得不将代码分成不同的部分,因为您不应同时读取和写入文件。它的订购方式如下:
打开文件进行阅读('r'
)并读入设备(最终会得到设备列表,字典或您想要使用的任何数据结构),然后关闭文件
处理数据 - 这是您可以增加设备数量的地方
打开文件进行书写('w'
),写行,然后关闭文件
你基本上已经拥有了所有的代码逻辑,只需解开它就可以分别完成3个建议的步骤。 :)
编辑:额外注意 - 由于您在阅读文件时将行拆分为':',因此您需要执行相反操作并在写回时':'.join(device)
。 ;)
答案 1 :(得分:0)
首先,不要为同一个文件打开多个文件句柄 - 这就是等待发生的灾难。
其次,更重要的是,您需要在添加新数字之前删除之前的数字 - 您执行此操作的方式实际上只是将数据附加到文件的末尾。为了实现你想要的东西,你必须做一些寻找和截断,例如:
def add_devices():
# no need to keep our files open while users provide their input
code = input("Enter device code: ")
amount = int(input("How many devices you are adding: "))
# you might want to validate the amount before converting to integer, tho
with open("uredjaji.txt", "r+") as f:
current_position = 0 # keep track of our current position in the file
line = f.readline() # we need to do it manually for .tell() to work
while line:
# no need to parse the whole line to check for the code
if line[:len(code) + 1] == code + ":": # code found
remaining_content = f.read() # read the rest of the file first
f.seek(current_position) # seek back to the current line position
f.truncate() # delete the rest of the file, including the current line
line = line.rstrip() # clear out the whitespace at the end
amount_index = line.rfind(":") + 1 # find the amount index position
current_amount = int(line[amount_index:]) # get our amount
# slice out the old amount, replace with the new:
line = line[:amount_index] + str(current_amount + amount) + "\n"
f.write(line) # write it back to the file
f.write(remaining_content) # write the remaining content
return # done!
current_position = f.tell() # cache our current position
line = f.readline() # get the next line
print("Invalid device code: {}".format(code))
add_devices()