【问题标题】:Why does the executable version of my Python program doesn't execute os.listdir and os.path.isdir correctly? OS is Windows 10为什么我的 Python 程序的可执行版本不能正确执行 os.listdir 和 os.path.isdir?操作系统是 Windows 10
【发布时间】:2025-12-20 16:55:06
【问题描述】:

我有这个程序打印一个字典,其中 文件夹名称 作为键,文件名 作为给定 path 的值:

import os
if os.name == 'nt': # Let's add some colors for the lulz
    from ctypes import windll
    k = windll.kernel32
    k.SetConsoleMode(k.GetStdHandle(-11), 7)

# Main method
the_dictionary_list = {}
print('\u001b[43mHi Sailor! I am "SAND-wich", a simple program built by @NoahVerner\033[0m')
print('\n')
time.sleep(2)
def check_path(infile):
    return os.path.exists(infile)    
        
first_entry = input('Tell me the path in which your folders with images are located:')

while True:
    
    if check_path(first_entry) == False:
        print('\n')
        print('This PATH is invalid!')
        first_entry = input('Tell me the RIGHT PATH in which your folders with ONLY images are located:')
        
    elif check_path(first_entry) == True:
        print('\n')
        final_output = first_entry
        break

print('This PATH has the following folders with the following files:')
print('\n')
for name in os.listdir(first_entry):
    if os.path.isdir(name):
        path = os.path.basename(name)
        print(f'\u001b[45m{path}\033[0m')
        list_of_file_contents = os.listdir(path)
        print(f'\033[46m{list_of_file_contents}')
        the_dictionary_list[path] = list_of_file_contents
print('\n')
print('\u001b[43mthe_dictionary_list:\033[0m')
print(the_dictionary_list)
print('\n')

.py 文件中,上面的代码按预期工作,没有任何错误。

将此程序导出为单个可执行文件后在cmd上使用以下语句:

pyinstaller --onefile --icon=./SAND-wich_icon.ico SAND-wich.py

我得到了这些文件夹:

dist 文件夹中包含我想要的 .exe 文件。

所以我将SAND-wich.exe 运行为Admin 必须先让我的 AVG Antivirus 停用(因为它也不会让该程序正常运行)

并且那个可执行文件确实认识到 path 我作为输入传递的确实是一个路径

但是,它不会返回具有预期值的所需字典它返回一个空字典

是什么导致了这个问题?假设我在两种情况下传递的path是同一个,并且只包含仅包含png图像的文件夹,而可执行文件将在其中运行的osWindows 10

【问题讨论】:

    标签: python-3.x dictionary debugging operating-system pyinstaller


    【解决方案1】:

    我想通了,实际上.py 代码中有些愚蠢

    for name in os.listdir(first_entry):
        backslash = "\\"
        if os.path.isdir(first_entry+backslash+name):
            path = os.path.basename(name)
            print(f'\u001b[45m{path}\033[0m')
            list_of_file_contents = os.listdir(first_entry+backslash+path)
            print(f'\033[46m{list_of_file_contents}')
            the_dictionary_list[path] = list_of_file_contents
    print('\n')
    print('\u001b[43mthe_dictionary_list:\033[0m')
    print(the_dictionary_list)
    print('\n')
    

    Diffchecker 上进行的比较,旧版本与新版本。

    【讨论】:

      最近更新 更多