Python文件整理脚本打包为exe后无法运行问题求助
问题描述
编写了一段用于文件整理的Python代码,直接运行时可正常按文件扩展名分类整理文件,但通过PyInstaller(--onefile参数)、Py2exe、auto-py-to-exe等工具打包为exe文件后,运行时CMD窗口闪一下就关闭,无法完成文件整理任务。无论是在dist文件夹内运行exe,还是将快捷方式移至其他目录运行,均无法正常工作,系统为Windows10。
原代码如下:
import fnmatch import os import shutil import pathlib temp_path = pathlib.Path(__file__).parent.resolve() path = pathlib.PureWindowsPath(fr'{temp_path}').as_posix() all_files = list() extension = set() #list of all the files and extensions for entry in os.scandir(path): if entry.is_file() and not fnmatch.fnmatch(entry, '*.ini'): all_files.append(entry.name) extension.add(os.path.splitext(entry)[1]) #creating the folders for folder in extension: folder_path = path+'/All_'+folder[1:]+'s/' #creating the folder os.mkdir(folder_path) #check in the list of the files for file in all_files: if file.endswith(folder): #moving the file from the current directory to the directory shutil.move(path+'/'+file, folder_path+file)
问题根源分析
__file__变量行为异常:Python脚本打包成单文件exe后,__file__指向的是系统临时解压后的脚本路径,而非exe实际运行的目录。原代码依赖该变量获取工作目录,导致操作的是临时目录而非目标目录,这是核心问题。- 无错误捕获机制:exe运行时的异常(如权限不足、目录已存在)会直接导致程序崩溃,且CMD窗口一闪而过,无法查看错误信息。
- 路径处理不严谨:手动拼接路径易出现格式问题,且
os.mkdir在目录已存在时会抛出异常,中断执行。
解决方案与修复代码
针对上述问题,修改后的代码如下:
import fnmatch import os import shutil import pathlib import sys def get_current_dir(): # 区分打包/未打包状态,获取正确的工作目录 if getattr(sys, 'frozen', False): return pathlib.Path(sys.executable).parent.resolve() else: return pathlib.Path(__file__).parent.resolve() def main(): try: path = get_current_dir() all_files = [] extension = set() # 遍历目录,排除ini文件和自身exe for entry in os.scandir(path): if entry.is_file(): if not fnmatch.fnmatch(entry.name, '*.ini') and not entry.name.endswith('.exe'): all_files.append(entry.name) ext = os.path.splitext(entry.name)[1] if ext: extension.add(ext) # 创建文件夹并移动文件 for folder in extension: folder_path = path / f"All_{folder[1:]}s" # 目录已存在则跳过创建 if not folder_path.exists(): folder_path.mkdir(parents=True) # 处理文件移动,避免覆盖已存在文件 for file in all_files: if file.endswith(folder): src = path / file dst = folder_path / file if dst.exists(): base, ext = os.path.splitext(file) counter = 1 while dst.exists(): dst = folder_path / f"{base}_{counter}{ext}" counter += 1 shutil.move(src, dst) input("文件整理完成,按任意键退出...") except Exception as e: input(f"运行出错:{str(e)}\n按任意键退出...") if __name__ == "__main__": main()
关键修改说明:
- 正确获取工作目录:通过
sys.frozen判断打包状态,返回exe所在目录而非临时路径。 - 异常捕获与窗口停留:用
try-except捕获所有异常,通过input()让窗口停留,方便查看错误信息或运行结果。 - 路径处理优化:使用pathlib的路径拼接替代手动字符串拼接,避免格式错误;创建目录前先检查是否存在,防止抛出异常。
- 额外防护逻辑:排除自身exe文件,避免误移动程序;处理目标文件已存在的情况,自动重命名防止覆盖。
内容的提问来源于stack exchange,提问作者Rashed
相关产品推荐
相关产品推荐

