UnboundLocalError:赋值前引用了局部变量“dest_eröff”

问题描述 投票:0回答:1
dest_dir = "I:\\My Drive\\Programmieren\\Buchführung"
        if not os.path.exists(dest_dir):
            os.mkdir(dest_dir)
        for file_name in os.listdir(dest_dir):
            if not file_name.startswith("Eröff"):
                start = str(date.today())
                dest_eröff = os.path.join(dest_dir, "Eröffnungbilanz_{}".format(start[:4]))
                with open(dest_eröff, 'w') as file:
                    file.write("Eroeffnungsbilanz ({})".format(start[:4]))
            else:
                dest_eröff = os.path.join(dest_dir, file_name)
        with open(dest_eröff) as file:
            start_year = int(str(file.read())[19:23])

为什么该代码不起作用。标题是错误。我认为变量“dest_eröff”在每种情况下都会被分配(无论文件是否存在)。如果它不存在,它将被创建(取决于实际年份),如果它存在,它将继续并分配变量。所以应该没问题吧

错误发生于

with open(dest_eröff) as file:
。感谢我得到的任何帮助。

python file
1个回答
0
投票

如果您的

dest_dir
中没有文件怎么办?

如果

os.listdir(dest_dir)
返回空列表,则 for 循环的内容将不会被执行,并且
dest_eröff
不会被赋值。

您可以在开始时将

dest_eröff
初始化为
None
,然后仅在
dest_eröff
有值时才尝试打开文件:

dest_dir = "I:\\My Drive\\Programmieren\\Buchführung"
if not os.path.exists(dest_dir):
    os.mkdir(dest_dir)

dest_eröff = None

for file_name in os.listdir(dest_dir):
    # your code unchanged

if dest_eröff is not None:
    with open(dest_eröff) as file:
        start_year = int(str(file.read())[19:23])

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