【问题标题】:I am getting unbound local error while pickle loading a file泡菜加载文件时出现未绑定的本地错误
【发布时间】:2020-04-29 05:08:29
【问题描述】:

我是。 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"
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()

【问题讨论】:

  • 您应该共享您的代码或导致相同问题的类似代码,并且您应该提供实际的错误消息而不仅仅是名称 - 但是,未绑定的本地错误通常是引用全局的结果函数内部的变量,而不将其声明为全局变量。如果这没有意义,请提供一些代码,然后有人可以调整您的代码以显示需要不同的地方。
  • 先生,请查看我添加到我的问题中的上述代码。错误是由于使用异常句柄还是其他原因?请指导我

标签: python function oop pickle file-handling


【解决方案1】:

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

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 完全按照您的要求执行并清理文件句柄,保证。

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

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

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 异常,如果你以可预测的方式腌制并且似乎 f1k1 的负载只服务目的是限制从kd 加载的元素数量,这是一种浪费。

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

【讨论】:

  • 谢谢。很多先生。我已经在代码中实现了您的所有修改。谢谢
  • 很高兴为您提供帮助 - 如果您认为答案回答了您的问题,请单击复选标记,以便问题显示为已回答,其他人也可以找到它
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多