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

问题描述 投票:0回答:1

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

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

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?

这是更好的方法,但不是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完全按照您的意图去做,并保证清理文件句柄。

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

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

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)

我不知道其余的代码,但是如果您以一种可预测的方式进行腌制,并且看来f1加载到k1中,则可能会摆脱EOF异常。目的是可能限制从kd加载多少个元素,这很浪费。]

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

© www.soinside.com 2019 - 2024. All rights reserved.