Nathan Shoesmith Nathan Shoesmith - 6 months ago 9
Python Question

Unexpected Writing To A File

I have a simple bit of code here, that will write to a file (reciepts) a code (for this example it is user inputted) and then the text '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())


However, when I read the file, I am getting some very unexpected results; (inputting 11111115 to test the else functionality, similar happens with a number in the products.csv file)

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


Instead of writing the code once, it has been written 17 times to the file.

I am appending to the file, due to my program requirements, but the file will be blank at the start of the program being run.

I have tried changing many aspects of the code, but have no idea why this is happening! Any ideas anyone?

(My csv file looks like this)


  • 34512340 Plain Brackets 1

  • 12395675 Yellow Pencil Sharpener 2

  • 56756777 Pack of 5 100mm Bolts 1

  • 90673412 L-Shaped Brackets 2

  • 12568673 Desk Tidy 3


Answer

If you want to check if the input exists inside the csv file and if not then write the Not Found message only once into the receipts file you can do something like this:

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()

Your code writes this message to the file for every line of your csv file since you put that code block inside your for loop. You also forgot the brackets at file.close()