如何写回更改的CSV文件

时间:2017-01-12 21:01:28

标签: python python-3.x csv

在标记为重复之前,我已阅读了与此类似的其他5个主题,但似乎无效。

我可以更改CSV文件中的值。但是,我无法弄清楚如何写回整个文件。我只能回写更改的行。

代码:

import csv

            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))
                    targetstock = str(targetstock)
                    newstock = str(newstock)
                    line[2]= int(newstock)
                    print(line)
                    with open("output.csv","w") as outfile:
                        newdata = csv.writer(outfile)
                        newdata.writerow(line)
                        if newstock<targetstock:
                            print("stock needs updating...please wait a moment")
                        else:
                            print("stock is fine")

Stock.csv:

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

output.CSV :(仅回写更改的行而不是文件的其余部分)

86947367    banana  1   40

我想:

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

1 个答案:

答案 0 :(得分:1)

您在此处反复覆盖输出文件:

with open("output.csv","w") as outfile:

将此行移至顶部:

with open("output.csv","w") as outfile, open("stock.csv") as infile:
    stockfile= csv.reader(infile)
    newdata = csv.writer(outfile)
        for line in stockfile:
             # ...
             newdata.writerow(line)
             # .... 

完整的工作示例:

import csv

GTIN = 'banana'
Quantity = 99

with open("output.csv","w") as outfile, open("stock.csv") as infile:
    stockfile= csv.reader(infile)
    newdata = csv.writer(outfile)
    for line in stockfile:
        if GTIN in line:
            currentstock= line[2]
            targetstock = line[3]
            newstock = (int(currentstock) - int(Quantity))
            targetstock = str(targetstock)
            newstock = str(newstock)
            line[2]= int(newstock)
            print(line)
            if newstock<targetstock:
                print("stock needs updating...please wait a moment")
            else:
                print("stock is fine")
        newdata.writerow(line)

输出:

86947367,banana,1,40
78364721,apple,50,20
35619833,orange,20,30
84716491,sweets,200,90
46389121,chicken,40,10
相关问题