我一直得到这个错误,我不知道要修理它

时间:2016-09-22 11:27:08

标签: python

我打开文件但是说文件没有打开。我坚持要做什么。我是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))

1 个答案:

答案 0 :(得分:3)

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

你需要

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

您在else声明中也遇到同样的错误。

你还应该考虑重构你的代码,因为你有很多文件开放和关闭。

编辑:正如@roganjosh提到的file是Python 2中的内置名称,因此您最好将所有file更改为例如fxcf2png