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

Python pickle加载文件时出现未绑定本地错误,python,function,oop,pickle,file-handling,Python,Function,Oop,Pickle,File Handling,我是。Pickle一个接一个地加载两个文件,我在关闭它们时遇到一个未绑定的本地错误。 我在打开文件时使用了异常处理,在except块中,它在关闭文件时显示未绑定的本地错误。 虽然我在异常块中使用了filenotfound,因为它是处理的必要异常。没有缩进错误,但我无法处理错误 "Traceback (most recent call last): File "d:\Python\t.py", line 648, in dispdeisel fdl=open("D:/Python/de

我是。Pickle一个接一个地加载两个文件,我在关闭它们时遇到一个未绑定的本地错误。 我在打开文件时使用了异常处理,在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"

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

。。然后下一行将永远不会执行,
fdl
将没有值

错误发生后,执行将在
之后继续,但EOFError和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?
这是更好的,但不是很像python,只是说明了如何解决您的问题-这根本不是我建议您如何写的

更接近您可能需要的:

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)
我不知道您的代码的其余部分,但是如果您以可预测的方式进行pickle,并且将
f1
加载到
k1
中似乎只是为了限制从
kd
加载多少个元素,那么您可能也可以摆脱EOF异常,这是浪费


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

您应该共享您的代码,或者导致相同问题的类似代码,并且您应该提供实际的错误消息,而不仅仅是名称-但是,未绑定局部错误通常是在函数中引用全局变量而未将其声明为全局变量的结果。如果这没有意义,请提供一些代码,有人可以调整您的代码以显示需要的不同之处。先生,请查看我添加到问题中的上述代码。出现错误是由于使用异常句柄还是其他原因?请参考《美山库指南》。非常感谢,先生。我已经实现了你对代码的所有修改。感谢您乐于帮助-如果您认为答案回答了您的问题,请单击复选标记,使问题显示为已回答,其他人也可以找到
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?
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)