2016-09-22 64 views
0

我打開文件,但是說文件沒有打開。我堅持要做什麼。我是python的新手。我不斷收到這個錯誤,我不知道它是否修復它

以下是錯誤:

Traceback (most recent call last): 
File "\\users2\121721$\Computer Science\Progamming\task3.py", line 43, in <module> 
file.write(barcode + ":" + item + ":" + price + ":" +str(int((StockLevel- float(HowMany))))) 
    ValueError: I/O operation on closed file. 

這裏是代碼:

#open a file in read mode 
file = open("data.txt","r") 
#read each line of data to a vairble 
FileData = file.readlines() 
#close the file 
file.close() 

total = 0 #create the vairble total 
AnotherItem = "y" # create 
while AnotherItem == "y" or AnotherItem == "Y" or AnotherItem == "yes" or AnotherItem == "Yes" or AnotherItem == "YES": 
     print("please enter the barcode") 
     UsersItem=input() 
     for line in FileData: 
       #split the line in to first and second section 
       barcode = line.split(":")[0] 
       item = line.split(":")[1] 
       price = line.split(":")[2] 
       stock = line.split(":")[3] 

       if barcode==UsersItem: 
        file = open("data.txt","r") 
        #read each line of data to a vairble 
        FileData = file.readlines() 
        #close the file 
        file.close() 
        print(item +"  £" + str(float(price)/100) + "  Stock: " + str(stock)) 
        print("how many do you want to buy") 
        HowMany= input() 
        total+=float(price) * float(HowMany) 
        for line in FileData: 
         #split the line in to first and second section 
         barcode = line.split(":")[0] 
         item = line.split(":")[1] 
         price = line.split(":")[2] 
         stock = line.split(":")[3] 
         if barcode!=UsersItem: 
          open("data.txt","w") 
          file.write(barcode + ":" + item + ":" + price + ":" +stock) 
          file.close() 
         else: 
          StockLevel=int(stock) 
          open("data.txt","w") 
          file.write(barcode + ":" + item + ":" + price + ":" +str(int((StockLevel-float(HowMany))))) 
          file.close() 
        open("data.txt","w") 
        StockLevel=int(stock) 
        print("Do you want to buy another item? [Yes/No]") 
        AnotherItem = input() 
     if AnotherItem == "n" or "N" or "no" or "No" or "NO": 
       print("total price: £"+ str(total/100)) 
+0

如果沒有'file = open(filename,mode)'any,那麼你沒有'file'對象創建瞭如何做'file.write'。 –

回答

3

if barcode!=UsersItem: 
    open("data.txt","w") 

您需要

if barcode!=UsersItem: 
    file = open("data.txt","w") 

還有你在else聲明中的錯誤。

而且你還應該考慮重構你的代碼,因爲你有很多的文件打開和關閉。

編輯:如@roganjosh提到file是在Python 2一個內置的名字,所以你最好改變file所有出現如f

+0

我不會建議他們使用'file'內建名作爲名字... – roganjosh

+0

@roganjosh'('file'in dir(__ builtin__))是False' –

+0

嗯,有趣。它是[Python 2](https://docs.python.org/2/library/functions.html#file)的內建,但不是[Python 3](https://docs.python.org/3/library /functions.html)。 – roganjosh

相關問題