Python打包exe遇PermissionError: [Errno 13]权限拒绝问题求助
解决PyPDF2打包exe后PermissionError权限问题
问题重现
用户代码(PyPDF2实现PDF旋转):
from PyPDF2 import PdfFileReader as rdr from PyPDF2 import PdfFileWriter as wtr import os SELF_PATH = os.path.dirname(__file__) file_name = 'pdf_file' in_path = fr'{SELF_PATH}\{file_name}.pdf' assert os.path.isfile(in_path) input = open(in_path, 'r+b') reader = rdr(input, strict=False) writer = wtr() orientation = reader.getPage(0).get('/Rotate') for pagenum in range(reader.numPages): page = reader.getPage(pagenum) page.rotateClockwise(180) writer.addPage(page) out_path = fr'{SELF_PATH}\_\{file_name}.pdf' assert os.path.isfile(out_path) output = open(out_path, 'wb') writer.write(output) output.close() input.close()
报错信息:
Traceback (most recent call last): File "tab.py", line 11, in <module> PermissionError: [Errno 13] Permission denied: 'C:\\Users\\paulo\\OneDrive\\Pastas\\Python\\Personal\\DocReader\\tab\\pdf_file.pdf' [25204] Failed to execute script 'tab' due to unhandled exception!
解决建议
- OneDrive路径限制:目标文件在OneDrive目录下,OneDrive的同步机制会限制文件读写权限,哪怕管理员身份也可能被拦截。把PDF移到本地非同步目录(如
C:\临时文件夹)测试,或暂时退出OneDrive再运行程序。 - 文件被占用:确认
pdf_file.pdf没有被PDF阅读器、浏览器等其他进程打开,关闭所有占用该文件的程序后重试。 - 修改文件打开模式:输入文件仅需读取权限,原代码用
'r+b'(读写模式)没必要,改成只读模式'rb'可避免权限冲突:input = open(in_path, 'rb') - 修复输出路径逻辑:原代码用
assert os.path.isfile(out_path)检查输出文件是否存在,但输出文件是要新建的,这个断言会报错;同时要确保输出目录_存在:out_dir = os.path.join(SELF_PATH, '_') if not os.path.exists(out_dir): os.makedirs(out_dir) out_path = os.path.join(out_dir, f'{file_name}.pdf') # 去掉assert os.path.isfile(out_path) output = open(out_path, 'wb') - 修正打包后的路径获取:auto-py-to-exe打包后,
os.path.dirname(__file__)会指向临时目录,改用以下代码获取exe实际运行路径:import sys if getattr(sys, 'frozen', False): SELF_PATH = os.path.dirname(sys.executable) else: SELF_PATH = os.path.dirname(__file__)
内容的提问来源于stack exchange,提问作者Paulo Mattos
相关产品推荐
相关产品推荐

