如何将.writerow()只放到csv文件中的1行?

时间:2016-10-02 14:51:16

标签: python file python-3.x csv

目前在我的代码中,它会更改第3行,但对于所有行,我希望它只更改用户输入的GTIN行。

当前代码:

file=open("stock.csv")
stockfile= csv.reader(file)
for line in stockfile:
    if GTIN in line:
        currentstock= line[2]
        targetstock = line[3]
        newstock = (int(currentstock) - int(Quantity))
        currentstock = str(currentstock)
        targetstock = str(targetstock)
        newstock = str(newstock)
    if newstock < targetstock :
        import csv
        reader = csv.reader(open('stock.csv',"r"))
        new = csv.writer(open('out.csv',"w"))
        for line in reader:
            new.writerow([line[0], line[1], newstock , line[3]])

文件中的输出(它会更改第3列中的所有数字):

86947367,banana,1,40
78364721,apple,1,20
35619833,orange,1,30
84716491,sweets,1,90
46389121,chicken,1,10

如何只更改用户输入的GTIN行?

2 个答案:

答案 0 :(得分:1)

使用csv模块: https://docs.python.org/3/library/csv.html

它有csv.reader()csv.writer()。将文件读入内存,迭代执行计算/替换,然后将每行写入新列表。最后,生成一个新的数据文件来替换旧的。

答案 1 :(得分:0)

在您使用csvreader之前我回答了您的其他一个问题,但它看起来已被删除。但原则是一样的。正如我在其中一条评论中所述,我认为你不应该继续重读/重读stock.txt。只需逐行读取它,然后逐行写入输出文件:

stock_number = input('Enter the stock number: ')
new_item = input('Enter item to add to above stock listing: ')

lines = []
with open('stock.txt', 'r') as infile:
    for line in infile:
        lines.append(line)

# can call this 'output.txt' if you don't want to overwrite original        
with open('stock.txt', 'w') as outfile:
    for line in lines:
        if stock_number in line:
            # strip newline, add new item, add newline
            line = '{},{}\n'.format(line.strip(), new_item)
        outfile.write(line)

编辑:这里是csv模块。这使得它更直接,因为csv模块为您提供了每行的字符串列表,然后您可以根据需要添加或修改它们。然后你可以逐行写回列表,而不必担心换行符或分隔符。

import csv

stock_number = input('Enter the stock number: ')
new_item = input('Enter item to add to above stock listing: ')
lines = []
with open('stock.txt', 'r') as infile:
    for line in csv.reader(infile):
        lines.append(line)

# change this to 'stock.txt' to overwrite original file
with open('output.txt', 'w') as outfile:
    writer = csv.writer(outfile)
    for line in lines:
        if stock_number in line:
            line.append(new_item)
        writer.writerow(line)

此外,你不应该在代码中间import真正SELECT group, avg(column) FROM table GROUP BY group, column HAVING avg(column) = ( SELECT TOP avg(column) FROM table GROUP BY group, column order by avg(column) ) 。导入通常位于文件的顶部。