简体   繁体   English

如何在文本文件中编辑特定行的一部分

[英]How to edit part of a specific line in a text file

I have a list of stock inventory. 我有一个库存清单。 For example: 例如:

1003, table, 12.99, 19.99, 45 1003,桌子,12.99、19.99、45

1004, chair, 3.99, 9.99, 32 1004,椅子,3.99、9.99、32

where it is written in the format: Product code, name, costprice, price, quantity 格式如下:产品代码,名称,成本价格,价格,数量

How would I be able to update the quantity so when orders are placed - decreases by 1 etc? 我如何更新数量,以便在下订单时-减少1等?

This is the code I have so far: 这是我到目前为止的代码:

def stockupdate():
itemname = input("Enter product name: ")
f = open('Stockinventory.txt', 'r') 
search = f.readlines() 
f.close() 
for line in search:
    lst = line.split(", ") #split 
    if str(itemname) == lst[1]: #Check to see if number entered is first parameter on list
        print ("SIN: %s" % lst[0])
        print ("Itemname: %s" % lst[1])
        print ("Retail price: %s" % lst[2])
        print ("Costprice: %s" % lst[3])
        print ("Quantity Available: %s" % lst[4])

This first section above just displays currently held product info to the user 上面的第一部分仅向用户显示当前持有的产品信息

choice = input("Would you like to update quantity? y/n")
if choice == 'y':
    newquantity = input("Enter new quantity: ")

    with open('Stockinventory.txt', 'r') as f:
        data = f.readlines()
    f.close()
    for line in data:
        lst = line.split(", ")
        if str(itemname) == lst[1]:
            lst[4] = str(newquantity)
            lst = line.join(", ")
            f = open('Stockinventory.txt', 'w')
            if itemname != lst[1]:
                f.write(line)
            else:
                f.write(lst)

At the moment I always end up deleting what is already in the text file 此刻,我总是最终删除文本文件中已经存在的内容

Thanks for your time, any help is appreciated 感谢您的宝贵时间,我们将不胜感激

I would read it using the cvs module. 我会使用cvs模块阅读它。 then place all the data in either a dict or put it in a pandas dataframe, 然后将所有数据放入dict或放入pandas数据框中,

In either, you can manipulate the content. 无论哪种方式,您都可以操作内容。

When finished, you can write your data back to disk 完成后,您可以将数据写回到磁盘

If you want to do it your way, you should open and close the file outside the loop, and write all lines, replacing the line you want altered. 如果要按自己的方式进行操作,则应在循环外打开和关闭文件,然后写所有行,替换要更改的行。 My experience is, that this method is too difficult, especially if you want to manipulate more complex items. 我的经验是,这种方法太困难了,尤其是当您要操作更复杂的项目时。

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

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