Python 将数组重写为文本文件时,需要将每个部分放在新行上

Python 将数组重写为文本文件时,需要将每个部分放在新行上,python,arrays,text,Python,Arrays,Text,我有一个股票系统。 数据按如下方式写入文件:(产品代码、名称、成本价格、价格、数量) 以下代码用于更新库存数量: def test(): items = [] itemname = input("Enter itemname: ") with open('Stockinventory.txt') as inputfile: for line in inputfile: items.append(line.strip().split(

我有一个股票系统。 数据按如下方式写入文件:(产品代码、名称、成本价格、价格、数量)

以下代码用于更新库存数量:

def test():
    items = []
    itemname = input("Enter itemname: ")
    with open('Stockinventory.txt') as inputfile:
        for line in inputfile:
            items.append(line.strip().split(','))

    with open('Stockinventory.txt') as inputfile:
        for num, line in enumerate(inputfile, 0):
            if itemname in line:
                newline = (items[num])
                newline = line.split(", ")
                print ("SIN: %s" % newline[0])
                print ("Itemname: %s" % newline[1])
                print ("Retail price: %s" % newline[2])
                print ("Costprice: %s" % newline[3])
                print ("Quantity Available: %s" % newline[4])
                choice = input("Would you like to update quantity? y/n")
                if choice == 'y':
                    newquantity = input("Enter new quantity: ")
                    newline[4] = newquantity
                    print(newline)
                    items[num] = newline
                    print(items)
                    writetrue = '1'
                else:
                    startup()

    if writetrue == '1':
        f = open('Stockinventory.txt', 'w')
        f.write(str(items))
        f.close()
    else:
        print("No change")
        startup()
代码正确地更改了数量,但当我将数组重写为文件时,它如下所示:

[['1004', 'table', '10', '20', '30'], ['1005', ' chair', ' 6', ' 13', ' 30'], ['1006', ' lamp', ' 2', ' 5', ' 10']]
在本例中,表的数量更改为30。
如何将数据像最初一样写回文件?

您正在编写整个列表的
str()
输出,而不是将行重新格式化为原始格式

用逗号重新连接行,在每行后面添加一个换行符:

with open('Stockinventory.txt', 'w') as f:
    for row in items:
        f.write(', '.join(row) + '\n')
如果您对逗号后的空格不太在意,也可以使用一次过编写列表:

import csv

with open('Stockinventory.txt', 'w', newline='') as f:
    csv.writer(f).writerows(items)
我当然会使用
csv
模块来读取您的文件:

import csv

with open('Stockinventory.txt', 'r', newline='') as f:
    items = list(csv.reader(f, skipinitialspace=True))
它可以一次性将整个文件读入列表列表

你把文件读了两遍;实际上没有必要,如果列表中已包含所有行,则不需要:

for row in enumerate(items):
    if row[1] == itemname:
        print("SIN: %s" % row[0])
        print("Itemname: %s" % row[1])
        print("Retail price: %s" % row[2])
        print("Costprice: %s" % row[3])
        print("Quantity Available: %s" % row[4])
        choice = input("Would you like to update quantity? y/n")
        if choice == 'y':
            newquantity = input("Enter new quantity: ")
            row[4] = newquantity
            print(', '.join(row))
            writetrue = '1'
        else:
            startup()

这里我们直接修改
;将
项目
再次写入
csv
文件将包括更改的数量。

您正在写入整个列表的
str()
输出,而不是将行重新格式化为原始格式

用逗号重新连接行,在每行后面添加一个换行符:

with open('Stockinventory.txt', 'w') as f:
    for row in items:
        f.write(', '.join(row) + '\n')
如果您对逗号后的空格不太在意,也可以使用一次过编写列表:

import csv

with open('Stockinventory.txt', 'w', newline='') as f:
    csv.writer(f).writerows(items)
我当然会使用
csv
模块来读取您的文件:

import csv

with open('Stockinventory.txt', 'r', newline='') as f:
    items = list(csv.reader(f, skipinitialspace=True))
它可以一次性将整个文件读入列表列表

你把文件读了两遍;实际上没有必要,如果列表中已包含所有行,则不需要:

for row in enumerate(items):
    if row[1] == itemname:
        print("SIN: %s" % row[0])
        print("Itemname: %s" % row[1])
        print("Retail price: %s" % row[2])
        print("Costprice: %s" % row[3])
        print("Quantity Available: %s" % row[4])
        choice = input("Would you like to update quantity? y/n")
        if choice == 'y':
            newquantity = input("Enter new quantity: ")
            row[4] = newquantity
            print(', '.join(row))
            writetrue = '1'
        else:
            startup()

这里我们直接修改
;再次将
项目
写入
csv
文件将包括更改的数量。

在这种情况下,不需要多次打开同一文件。你可以一次完成这一切。如果您不需要任何标准库导入,并且可读性对您很重要,那么您可以对其进行重构:

itemname = raw_input("Enter item name\n>>>")

with open("Stockinventory.txt", "r+") as file:
    # Search for item (per line)
    while True:
        position = file.tell()
        thisline = file.readline()
        if itemname in thisline:
            break

    # Print result
    for tag, val in zip(["SIN", "Itemname",
                         "RetailPrice", "Costprice",
                         "Quantity Available"],
                         thisline.split(", ")):
        print tag, ":", val

    # Query update
    choice = raw_input("Would you like to update "
                       "quantity?\n>>>")
    if choice in ("y", "Y"):
        newquan = raw_input("Enter new quantity\n>>>")
        newline = "".join([thisline.rsplit(",",1)[0],
                           ", ", newquan, "\n"])
        remline = file.read()
        file.seek(position)
        file.write(newline + remline)

在这种情况下,不需要多次打开同一文件。你可以一次完成这一切。如果您不需要任何标准库导入,并且可读性对您很重要,那么您可以对其进行重构:

itemname = raw_input("Enter item name\n>>>")

with open("Stockinventory.txt", "r+") as file:
    # Search for item (per line)
    while True:
        position = file.tell()
        thisline = file.readline()
        if itemname in thisline:
            break

    # Print result
    for tag, val in zip(["SIN", "Itemname",
                         "RetailPrice", "Costprice",
                         "Quantity Available"],
                         thisline.split(", ")):
        print tag, ":", val

    # Query update
    choice = raw_input("Would you like to update "
                       "quantity?\n>>>")
    if choice in ("y", "Y"):
        newquan = raw_input("Enter new quantity\n>>>")
        newline = "".join([thisline.rsplit(",",1)[0],
                           ", ", newquan, "\n"])
        remline = file.read()
        file.seek(position)
        file.write(newline + remline)

如何
f.write('\n'.join(','.join(row)for row in items))
@lejlot:当然,这也行,但是循环可能更可读一些。请注意,您的版本不会在最后一行之后写换行符,这在编写文本文件时通常是需要的。最后一行换行符只是关于
f.write('\n'.join(','.join(row))for row in items)+'\n')
,我认为这种方法的唯一问题实际上是构造(可能)巨大的字符串
f.write怎么样(“\n”.join(“,”.join(row)表示项目中的行))
@lejlot:当然,这也行,但是循环可能更可读一些。请注意,您的版本不会在最后一行之后写换行符,这通常是在编写文本文件时需要的。最后一行换行符仅是关于
f.write(“\n”.join(“,”.join(row)表示项目中的行)+'\n')
,我认为这种方法的唯一问题实际上是构造一个(可能)巨大的字符串