2016-09-22 5 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'オブジェクトを作成していないと、' file = open(filename、mode) 'が存在しない場合、' file.write'をどのように行うことができますか? –

答えて

3

にあなたが必要

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

がありますが、

また、elseと同じエラーが表示されます。

また、コードのリファクタリングも考慮する必要があります。ファイルのオープンとクローズが多いからです。

編集:@roganjoshは、あなたがより良い例するfileのすべてのオカレンスを変更したいのでfileは、Pythonの2の組み込み名です述べたようにf

+0

名前として組み込みの 'file'を使用することをお勧めしません。 – roganjosh

+0

@roganjosh'( '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

関連する問題