简体   繁体   中英

Reading the next line of a file

im new to this site and I know alot of people aren't very happy when somebody asks a question previously asked. However, I wish to ask despite it being previously asked beacause all the answers I found did not make much sense to me (im new to python!), so I was wondering if somebody could dumb it down for me or directly correct my code.

Im writing a code where the user inputs a GTIN-8 code and it searches a csv excel file for that code, it then reads the appropriate information about the product (price,ect...) and prints it out. However I cant search the second line of the file for some reason. Here is my code:

#csv is imported to read/write to the file
import csv

#Each Product is printed alongside it's GTIN-8 code and Price
print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~")
print("~ Welcome to Toms bits and bobs ~")
print("Pencil,          12346554, £0.40")
print("50 Staples,      12346882, £1.00")
print("50 Paper Clips,  12346875, £1.20")
print("Large Eraser,    12346844, £1.50")
print("100 A4 Sheets,   12346868, £2.00")
print("100 A3 Sheets,   12346837, £2.50")
print("25 Byro Pens,    12346820, £2.20")
print("Handwriting Pen, 12346899, £5.50")
print("50 Split Pins,   12346813, £0.60")
print("Office Chair,    12346912, £25.00")
print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~")

#The file is opened and the user inputs the code for the product they
#wish to find.
file = open("Product_list.csv", "r")
purchase = input(print("Please enter the GTIN-8 code of the product you wish to purchase e.g 12346554"))
line = file.readline()
data = line.split(",")

if data[0] == purchase:
    while(line):
        print ("Product: ", data[1])
        print ("GTIN-8 code: ", data[0])
        print ("Stock: ", data[2])
        print ("Description: ", data[3])
        print ("Price: ", data[4])
        line = file.readline()
        break

else:
    print("Product not found")


file.close()`

You are reading second line but because of the break , you never get a chance to use it since your code always breaks out of while loop if it enters there. Just remove it and your code should work fine.

Also, assuming your syntax is correct on this line.

purchase = input(print("Please enter the GTIN-8 code of the product you wish to purchase e.g 12346554"))  
                 ^^^^^This will cause a syntax error. You should remove this print as well

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM