在python中将列表写入文件?

时间:2016-02-09 17:57:49

标签: python text-files

我有一个产品文件,格式如下:

12345670:Cadbury:0.50:100
12647859:Chips:1.50:50
16728769:Crisps:1.00:60
11111115:Olives:1.50:100
22222220:Blackberries:1.00:100
30298712:Gluestick:1.99:50
19832876:Cake:2.00:50
14054310:Phone:70.50:5
19208114:Banana:0.50:75
10928738:Raisins:0.75:100

第一部分是产品代码。第二个是描述。第三是价格,第四是库存水平。

程序将在用户输入产品代码后询问用户所需的产品数量。但是如何更新产品文件中的库存。每当我尝试它时,它会用空格覆盖我的整个文件。请帮忙

2 个答案:

答案 0 :(得分:0)

你没有正确解释,坦率地说你的问题不是一个明确的问题,而是一个代码编写请求(这违反了StackOverflow的政策)。所以这就是你得到的:

contents包含每行的列表,此列表的每一行都包含4个分隔数据的列表。

with open('file.txt', 'r') as file:
    contents = [line.split(':') for line in file]

然后您可以修改(contents[index_num] = altered_value)或添加(contents.append(new_value))无论您要修改或添加的内容,并将其写回文件,如下所示:

with open('file.txt', 'w') as file:
    for item in contents:
        print(item, file=file)

这是一个快速修复!

答案 1 :(得分:0)

您需要读取整个文件,对其进行处理,然后将整个文件写回。修改文件实际上是不可能的。

这可以通过使用Python的csv库来帮助解析文件,方法是指定参数分隔符是:。通过这样做,每个条目被自动读入作为参数列表,例如, ['12647859', 'Chips', '1.50', '50']

import csv

stock_file = 'stock.csv'

stock = {}
with open(stock_file, 'rb') as f_stock:
    csv_stock = csv.reader(f_stock, delimiter=':')

    for cols in csv_stock:
        stock[cols[0]] = cols
    print stock

while True:
    product_code = raw_input("Please enter product code: ")
    product_quantity = int(raw_input("Please enter quantity: "))

    try:
        stock[product_code][3] = int(stock[product_code][3]) + product_quantity
        break
    except KeyError, e:
        print "Unknown product ID, try again"

with open(stock_file, 'wb') as f_stock:
    csv_stock = csv.writer(f_stock, delimiter=':')
    csv_stock.writerows(stock.values())

所以对于以下输入:

Please enter product code: 12345670
Please enter quantity: 1000

股票档案将按如下方式更新:

12647859:Chips:1.50:50
11111115:Olives:1.50:100
16728769:Crisps:1.00:60
10928738:Raisins:0.75:100
19208114:Banana:0.50:75
30298712:Gluestick:1.99:50
12345670:Cadbury:0.50:1100
22222220:Blackberries:1.00:100
19832876:Cake:2.00:50
14054310:Phone:70.50:5

请注意,由于条目存储在字典中,因此不会在文件中维护排序。如果需要,则可以将其转换为使用OrderedDict

注意,如果您不被允许使用csv库,可以重做如下:

stock_file = 'input.txt'

stock = {}
with open(stock_file, 'rb') as f_stock:
    for line in f_stock:
        cols = line.split(':')
        stock[cols[0]] = [col.strip() for col in cols]

while True:
    product_code = raw_input("Please enter product code: ")
    product_quantity = int(raw_input("Please enter quantity: "))

    try:
        stock[product_code][3] = str(int(stock[product_code][3]) + product_quantity)
        break
    except KeyError, e:
        print "Unknown product ID, try again"

with open(stock_file, 'wb') as f_stock:
    f_stock.write('\n'.join(':'.join(line) for line in stock.values()))