我知道无法写入csv文件中的特定单元格,但在我的代码中,如果满足命令,我一直在尝试更改值。因此,如果用户输入的数字高于目标股票(合适的股票数量,最后一列),那么它将从当前股票(第3列)中减去输入的数字,然后回写新股票。我的代码存在问题它写了一切:
在写入csv之前:
86947367,banana,100,40
78364721,apple,50,20
35619833,orange,20,30
84716491,sweets,200,90
46389121,chicken,5,10
写入csv后:
86947367,banana,2,40
正如您所看到的那样,它会覆盖整个股票文件,其中包含股票已更改的行。
我目前的代码:
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)
if newstock < targetstock :
with open('stock.csv', 'r') as infile:
oldata = csv.reader(infile)
for row in oldata:
if GTIN == row[0]:
newstock=int(row[2]) - int(Quantity)
row[2] = newstock
print(row)
with open("output.csv","w") as outfile:
newdata = csv.writer(outfile)
newdata.writerow(row)
else:
print("lel")
所有帮助表示赞赏。
答案 0 :(得分:0)
我的大部分答案都来自this one。抄袭,我建议使用fileinput模块。在遍历各行时,您可以print()
编写文件。我无法完全理解您的问题,但我认为此代码段可以完成大部分工作。
import csv
import fileinput
# setting some things for what I think applies to your example
GTIN = "86947367"
Quantity = "98"
# set inplace=False if you do not want to modify the file inplace
# for example to debug you can set it to false and look at the output
with fileinput.FileInput(files=['stock.csv'], inplace=True, backup='.bak') as input:
for line in input:
if GTIN in line:
# a little workaround to parse a string as csv
csv_elements = [i for i in csv.reader([line])][0]
new_stock = int(csv_elements[2]) - int(Quantity)
target_stock = int(csv_elements[3])
# check for your condition here
if new_stock < target_stock:
# update appropriate element in csv_elements
csv_elements[2] = str(new_stock)
# join everything back together with commas
print(",".join(csv_elements))
else:
# if it's not the stock to update, just print the same line
# set end to empty string to avoid extra newlines
print(line, end="")
CSV解决方法位于最底层 - Python CSV