pickle 加载文件时出现未绑定的本地错误

I am getting unbound local error while pickle loading a file

我是。 Pickle 一个一个地加载两个文件,关闭它们时出现未绑定的本地错误。 我在打开文件时使用了异常处理,并且在关闭文件时在 except 块中显示未绑定的本地错误。 尽管我在异常块中使用了 filenotfound,因为它是 handle.no 缩进错误的必要异常,但我无法处理错误说明。

"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()

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

tdc=open("D:/Python/deisel/collection.txt","rb+")

.. 那么下一行将永远不会被执行并且 fdl 将没有值。

出错后,在except EOFError and FileNotFoundError:后继续执行,到达这一行:

fdl.close()

由于从未定义 fdl(因为跳过了该行),因此它没有任何价值,这就是您出错的原因。

修复它的一种方法是更干净地处理异常:

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?

这更好,但不是很 Pythonic,只是说明了您可以如何解决您的问题 - 这根本不是我建议您编写的方式。

更接近您可能需要的:

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?

with 完全按照您的要求执行并清理文件句柄,保证。

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

一般来说,如果您希望异常发生,请不要使用异常,而是直接编写您期望的代码 - 它更易于阅读和维护,而且通常性能更好:

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)

我不知道你的其余代码,但你也可以摆脱 EOF 异常,如果你以可预测的方式进行 pickle,并且 f1 的负载似乎进入 k1 仅用于限制从 kd 加载元素的数量,这很浪费。

请注意,对于每个示例,代码如何变得更具可读性和更短。更短本身并不是一件好事,但如果您的代码变得更易于阅读和理解,性能更好并且顶部更短,那么您就知道自己走在正确的轨道上。