我这里有一些简单的代码,它会写入一个文件(reciepts)一个代码(对于这个例子,它是用户输入的),然后是文本'Product Not Found。
import csv
code=input("TEST INPUT:")
with open('products.csv', newline='') as f:
reader = csv.reader(f, delimiter='\t')
for line in f:
if code in line:
print(line)
else:
f = open("reciepts","a")
f.write(code)
f.write("Product Not Found")
f.close
f = open("reciepts","r")
print(f.read())
然而,当我阅读文件时,我得到了一些非常意外的结果; (输入11111115来测试else功能,类似于products.csv文件中的数字)
11111115Product Not Found11111115Product Not Found11111115Product Not Found11111115Product Not Found11111115Product Not Found11111115Product Not Found11111115Product Not Found11111115Product Not Found11111115Product Not Found11111115Product Not Found11111115Product Not Found11111115Product Not Found11111115Product Not Found11111115Product Not Found11111115Product Not Found11111115Product Not Found11111115Product Not Found11111115Product Not Found
而不是编写一次代码,它已被写入文件17次。
由于我的程序要求,我将附加到该文件,但该文件在程序运行开始时将为空白。
我尝试更改代码的许多方面,但不知道为什么会发生这种情况!任何人的想法?
(我的csv文件看起来像这样)
答案 0 :(得分:2)
如果要检查csv文件中是否存在输入,如果不存在,则只将Not Found
消息写入收据文件中,您可以执行以下操作:
with open('products.csv',newline='') as f:
reader = csv.reader(f, delimiter='\t')
found = False
for line in f:
if code in line:
print(line)
found = True
break
if not found:
f = open("reciepts","a")
f.write(code)
f.write("Product Not Found")
f.close()
您的代码将此消息写入csv文件的每一行的文件,因为您将该代码块放在for
循环中。您还忘记了file.close()