如何解决带进度条文件复制中的PermissionError: [Errno 13]权限拒绝问题
解决PermissionError: [Errno 13] Permission denied错误
问题根源
- 源路径指向文件夹而非文件:你代码里的
src_pathdream = r'C:\Users\Sn00f\Desktop\Dreamcast'是一个文件夹路径,但open()函数仅能打开文件,直接对文件夹调用open()会触发权限拒绝错误。 - 目标路径拼写错误:
dest_pathdream = r'C:\AppMetier\Deamcast'里的Deamcast是拼写失误,应为Dreamcast。 - 代码逻辑不匹配需求:当前代码是为单个文件复制设计的,但你实际需要复制整个文件夹,需递归处理子文件和子文件夹。
修复方案
1. 修正路径问题
确认源路径为文件夹(后续代码会处理遍历),修正目标路径的拼写,并提前创建目标文件夹(避免因文件夹不存在引发错误)。
2. 调整代码实现文件夹递归复制
使用os.walk()遍历源文件夹下的所有文件,逐个复制并累计进度条总大小,实现带进度的文件夹复制。
修改后的代码如下:
import os from tqdm import tqdm def installdreamcast(): src_pathdream = r'C:\Users\Sn00f\Desktop\Dreamcast' dest_pathdream = r'C:\AppMetier\Dreamcast' # 修正拼写错误 # 提前创建目标文件夹(不存在则创建) os.makedirs(dest_pathdream, exist_ok=True) # 计算源文件夹所有文件的总大小 total_size = 0 for root, dirs, files in os.walk(src_pathdream): for file in files: file_path = os.path.join(root, file) total_size += os.path.getsize(file_path) # 遍历并复制文件 with tqdm(ncols=60, total=total_size, bar_format='{l_bar}{bar} | Remaining: {remaining}') as pbar: for root, dirs, files in os.walk(src_pathdream): # 在目标路径创建对应的子文件夹 relative_path = os.path.relpath(root, src_pathdream) target_dir = os.path.join(dest_pathdream, relative_path) os.makedirs(target_dir, exist_ok=True) for file in files: src_file = os.path.join(root, file) dest_file = os.path.join(target_dir, file) # 复制单个文件 with open(src_file, 'rb') as f: with open(dest_file, 'wb') as n: while True: buf = f.read(8192) if not buf: break n.write(buf) pbar.update(len(buf)) print("It's GOOOOOOOOOOOOOOOOOOOOOOOOD")
额外注意事项
- 权限验证:如果目标文件夹
C:\AppMetier是系统目录,需以管理员身份运行Python程序。 - 文件覆盖处理:若需跳过已存在文件,可在复制前判断
dest_file是否存在,按需选择跳过或覆盖逻辑。
内容的提问来源于stack exchange,提问作者Sn00f
相关产品推荐
相关产品推荐

