权限错误:[Errno 13] 权限被拒绝。如何重写代码以将文件夹“b”中的文件夹“a”放置到文件夹“c”

问题描述 投票:0回答:1
def tdata_move():
    number_of_acc = len([file for file in os.scandir(fr"D:\tdata for accs")])
    for item in range(0, number_of_acc):
        for folder in os.listdir(r"D:\tdata for accs"):
            shutil.copyfile(fr"D:\tdata for accs\{folder}", fr"D:\accs_test\acc{item + 1}")

错误:

PermissionError: [Errno 13] Permission denied: 'D:\\data for accs\\068686868'

所以在这里我尝试创建一个循环,将位于文件夹“b”中的文件夹“a”放入文件夹“c”中。 看起来像这样:

acc1 should store "data" folder from folder "D:\data for accs\068686868\data"
acc2 should store "data" folder from folder "D:\data for accs\049193193\data"
acc3 should store "data" folder from folder "D:\data for accs\318418317\data"

但是我收到:

PermissionError: [Errno 13] Permission denied: 'D:\data for accs \

所以现在它无法从068686868文件夹读取数据,没有权限。

python shutil python-os
1个回答
0
投票

权限错误是由于使用

copyfile
造成的。使用
copytree
作为目录:

import os
import glob
import shutil

original = 'org'
destination = 'dest'

num = 1
for item in glob.glob(os.path.join(original, '*/')):  # Generates paths to directories only
    target = os.path.join(destination, f'acc{num}')
    print(f'Copying {item} to {target}...')
    shutil.copytree(item, target)
    num += 1

给定一个目录树:

───org
    │   file4.txt
    ├───1
    │       file1.txt
    ├───2
    │       file2.txt
    └───3
            file3.txt

除了不在目录中的 file4.txt 之外的所有内容都将被复制到

dest
:

Copying org\1\ to dest\acc1...
Copying org\2\ to dest\acc2...
Copying org\3\ to dest\acc3...

结束树:

├───dest
│   ├───acc1
│   │       file1.txt
│   ├───acc2
│   │       file2.txt
│   └───acc3
│           file3.txt
└───org
    │   file4.txt
    ├───1
    │       file1.txt
    ├───2
    │       file2.txt
    └───3
            file3.txt
© www.soinside.com 2019 - 2024. All rights reserved.