简体   繁体   English

如何在Python中更改txt文件的指定部分

[英]How to change specified part of txt file in Python

I have txt file like this: 我有这样的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

(where tw001 to tw004 is code of some devices and last part of a line is amount 5,1,4,3) (其中tw001至tw004是某些设备的代码,一行的最后一部分是数量5,1、4、3)

Now I'm trying to add amount to devices with specified code: 现在,我尝试使用指定的代码向设备添加金额:

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()

My problem is that sum of specified device is just add to the end of txt file. 我的问题是指定设备的总和只是添加到txt文件的末尾。 How to fix that? 如何解决? (For example if I enter tw004 and add 3 sum 8 is just aded to tw003:Huawei P9:Huawei:Mobilni telefon:3 8 ) (例如,如果我输入tw004并加上3和8,那么tw003:Huawei P9:Huawei:Mobilni telefon:3 8

Since you are wanting to update the same file, you will have to separate the code into distinct parts, since you shouldn't read and write to a file at the same time. 由于您要更新相同的文件,因此您必须将代码分成不同的部分,因为您不应同时读写文件。 It could be ordered like: 可以像这样订购:

  1. open the file for reading ( 'r' )and read in the devices (you'll end up with a list of devices, or dictionary, or whatever data structure you want to use), and close the file 打开文件进行读取( 'r' )并读入设备(您最终会得到设备列表,字典或要使用的任何数据结构),然后关闭文件

  2. process the data - this is where you can increase the number of devices and such 处理数据-在这里您可以增加设备数量,例如

  3. open the file for writing ( 'w' ), write the lines, and close the file 打开要写入的文件( 'w' ),编写各行,然后关闭文件

You basically have all the code logic already, just need to untangle it so that you can do the 3 suggested steps separately. 您基本上已经具有所有代码逻辑,只需解开它们,以便可以分别执行建议的3个步骤。 :) :)

Edit: extra note - since you split the lines on ':' when reading the file, you will need to do the reverse and ':'.join(device) when writing it back. 编辑:特别注意-由于在读取文件时将':'上的行分割开,因此在写回文件时,需要进行反向操作和':'.join(device) ;) ;)

First of all, don't open multiple file handles to the same file - that's a disaster waiting to happen. 首先,不要打开同一个文件的多个文件句柄-这是灾难的等待。

Second, and more to the point, you need to remove the previous number before you add a new one - the way you're doing it is essentially just appending the data to the end of the file. 其次,更重要的是,您需要在添加新数字之前删除先前的数字-实际上,此方法只是将数据附加到文件末尾。 You'll have to do a bit of seeking and truncating in order to achieve what you want, something like: 您必须进行一些搜索和删节操作才能实现所需的功能,例如:

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()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM