我在泡菜加载文件时遇到未绑定的本地错误

时间:2020-04-29 05:08:29

标签: python function oop pickle file-handling

我是。泡菜一个接一个地加载两个文件,我在关闭它们时遇到了未绑定的本地错误。 我在打开文件时使用了异常处理,在except块中,关闭文件时显示了未绑定的本地错误。 尽管我在异常块中使用了filenotfound,因为它是处理异常的必要异常。没有缩进错误,我只是无法处理错误说明。

"Traceback (most recent call last):
  File "d:\Python\t.py", line 648, in dispdeisel
    fdl=open("D:/Python/deisel/"+str(z1)+".txt","rb+")
FileNotFoundError: [Errno 2] No such file or directory: 'D:/Python/deisel/Wed Apr 29 2020.txt'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "d:\Python\t.py", line 820, in <module>
    b.dispdeisel()
  File "d:\Python\t.py", line 664, in dispdeisel
    fdl.close()
UnboundLocalError: local variable 'fdl' referenced before assignment"
k1=[]

        try:
            tdc=open("D:/Python/deisel/collection.txt","rb+")
            fdl=open("D:/Python/deisel/"+str(z1)+".txt","rb+")
            while True:
                self.f1=pickle.load(tdc)
                self.fd=pickle.load(fdl)
                k1.append(self.f1)
                kd.append(self.fd)
        except EOFError and FileNotFoundError:
            qa=0
            for i in kd:
                if "L"in i:
                    qa1=i[:-1]
                    qa=qa+int(qa)
                else:
                    qa=qa+int(i[0])
            print (" Total Collection for Deisel on date ",z1,"is",qa)
            tdc.close()
            fdl.close()

1 个答案:

答案 0 :(得分:0)

在您的示例代码中,到达此行(并导致错误)时:

b'aaaaaaaaaaaaaaaaaaaaaaaaaa' 59
b'x\x9cKL\xc4\x05\x00\x85\x19\t\xdb' 44
b'aaaaaaaaaaaaaaaaaaaaaaaaaa' 59

..那么下一行将永远不会执行,并且tdc=open("D:/Python/deisel/collection.txt","rb+") 将没有值。

出现错误后,在fdl之后继续执行,并到达以下行:

except EOFError and FileNotFoundError:

由于从未定义fdl.close() (因为跳过了该行),因此它没有任何值,这就是导致错误的原因。

一种解决方法是更干净地处理异常:

fdl

这是更好的方法,但不是Python风格,仅说明了如何解决问题-根本不建议您编写此方法。

更贴近您的需求

class SomeClass:
    def some_method(self, z1):
        # initialisation
        qa = 0
        kd = []
        k1 = []
        try:
            tdc = open("D:/Python/deisel/collection.txt","rb+")
            try:
                fdl = open("D:/Python/deisel/"+str(z1)+".txt","rb+")
                try:
                    try:
                        while True:
                            self.f1 = pickle.load(tdc)
                            self.fd = pickle.load(fdl)
                            k1.append(self.f1)
                            kd.append(self.fd)
                    except EOFError:
                        pass  # no message needed, but not the nicest way to use the exception
                    for i in kd:
                        if "L" in i:
                            # this bit makes no sense to me, but it's not relevant
                            qa1 = i[:-1]
                            qa = qa + int(qa)
                        else:
                            qa = qa + int(i[0])
                    print(" Total Collection for Deisel on date ", z1, "is", qa)
                finally:
                    tdc.close()
                    fdl.close()
            except FileNotFoundError:
                tdc.close()  # this is open, closing it
                pass  # some error message perhaps?
        except FileNotFoundError:
            pass  # some error message perhaps?

import pickle class SomeClass: def some_method(self, z1): # initialisation qa = 0 kd = [] k1 = [] try: with open("D:/Python/deisel/collection.txt","rb+") as tdc: try: with open("D:/Python/deisel/"+str(z1)+".txt","rb+") as fdl: try: while True: self.f1 = pickle.load(tdc) self.fd = pickle.load(fdl) k1.append(self.f1) kd.append(self.fd) except EOFError: pass # no message needed, but not the nicest way to use the exception for i in kd: if "L" in i: # this bit makes no sense to me, but it's not relevant qa1 = i[:-1] qa = qa + int(qa) else: qa = qa + int(i[0]) print(" Total Collection for Deisel on date ", z1, "is", qa) except FileNotFoundError: pass # some error message perhaps? except FileNotFoundError: pass # some error message perhaps? 完全按照您的意图进行操作,并保证清理文件句柄。

这仍然存在从文件中获取多个泡菜的问题,但不能保证两个泡菜的数量都相同-如果您自己编写这些泡菜,为什么不泡菜的对象列表并避免这种混乱呢? / p>

通常,如果您期望发生异常,请不要使用异常,而应直接根据您的期望进行编码-易于阅读和维护,并且通常表现更好:

with

我不知道其余的代码,但是如果您以一种可预测的方式进行腌制,并且看来{{1} }}仅用于限制从import pickle from pathlib import Path class SomeClass: def some_method(self, z1): # initialisation qa = 0 kd = [] k1 = [] fn1 = "D:/Python/deisel/collection.txt" fn2 = "D:/Python/deisel/"+str(z1)+".txt" if not Path(fn1).is_file() or not Path(fn2).is_file(): return # some error message perhaps? with open(fn1, "rb+") as tdc: with open(fn2, "rb+") as fdl: try: while True: # not using self.f1 and .fd, since it seems they are just local # also: why are you loading k1 anyway, you're not using it? k1.append(pickle.load(tdc)) kd.append(pickle.load(fdl)) except EOFError: pass # no message needed, but not the nicest way to use the exception for i in kd: if "L" in i: qa1 = i[:-1] qa = qa + int(qa) else: qa = qa + int(i[0]) print(" Total Collection for Deisel on date ", z1, "is", qa) 加载多少个元素的目的,这很浪费。

请注意,在每个示例中,代码如何变得更具可读性和更短。短一点本身不是一件好事,但是,如果您的代码变得更易于阅读和理解,更好地执行并且在顶部更短,则表示您处在正确的轨道上。