2016-02-09 85 views
-2

我正在嘗試編寫一個代碼(在python上),它將讀取一個包含產品列表的文件,每個產品的GTIN-8代碼,每個產品的描述,庫存和價格。試圖讀取文件-python

到目前爲止,我設法讀取最上面一行,打印出其細節,但我不確定如何閱讀下一行。任何幫助?請儘量保持簡單:)

PP

代碼爲我的男人Doroskevic:

#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 purchase == "12346554": 
    while(line): 
     print ("Product: ", data[0]) 
     print ("GTIN-8 code: ", data[1]) 
     print ("Stock: ", data[2]) 
     print ("Description: ", data[3]) 
     print ("Price: ", data[4]) 
     line = file.readline() 
     break 
if purchase == "12346882": 
    while(line): 
     print ("Product: ", data[0]) 
     print ("GTIN-8 code: ", data[1]) 
     print ("Stock: ", data[2]) 
     print ("Description: ", data[3]) 
     print ("Price: ", data[4]) 
     line = file.readline() 
     break 

file.close() 
+2

嗨,你能證明你的代碼? –

回答

-3

例子:

path = 'c:/users/-e/my documents/text.txt' 

with open(path, 'r') as file: 
    data = file.readlines() 

    for line in data: 
     print(line, end='') 

輸出:

Are all the good times dead and gone? 
Come and go and come and go (come and come and go) 
I got a lot of friends who are stars 
But some are just black holes 

By Fall out boy - 27 

函數.readlines()將讀取文件中的所有行爲list結構。這將允許根據需要進行進一步的操作。

參考:

Python Documentation
Python TutorialsPoint

+0

您能否提供一個鏈接來描述這個polcy的描述?如果沒有提供鏈接,上述答案的質量是否令人滿意?如果是的話,你還可以提供一個鏈接到標準?否則 - 如果您將刪除倒票,我將不勝感激。 –

+0

我沒有足夠的聲望(即時通訊新:D)給它一個打勾雖然 –

+0

在答覆Altoyr: –