简体   繁体   中英

Copy certain files to other folder using Python ( File Management in Python )

I want to check a folder and all subfolders if a certain file exists. If exists then I want to copy that in another folder. I have tried the following stuff

def copy_files(src, dest):
    files = os.listdir(src)
    for f in files:
        shutil.copy(src +f , dest)

for root, dirs, files in os.walk(my_path):
    for f in files:
        if f.endswith(".7z"):
            print("found files: " , f)
            copy_files(my_path, arch_dest)

On the copy_files function works. But it does not work inside the for the loop.

I am getting the following error:

Permission denied: './data/f_1'

What am I doing wrong?

The Copy function works in other folders. But in this loop, it does not work. I need to make it work inside the loop.

Update:

I am assuming the problem is more with the path, I have checked inside the for loop it shows the home directory where it is. with print(os.getcwd())

Do I need to then go to the folder while checking the file?

Found the solution finally. I knew it in is because of the Root/Path. It has nothing to do with admin/sudo stuff.

It can be done as follows.

for r,d,files in os.walk(my_path):
    for f in files:
        print(r)
        shutil.copy(r + "/" + f, dest_path)

Try using a try/except around the loop to ignore the files you dont have permission to search:

try:
    for root, dirs, files in os.walk(my_path):
        for f in files:
            if f.endswith(".7z"):
                print("found files: " , f)
                copy_files(my_path, arch_dest)
except OSError:
    pass

您需要以sudo用户身份运行python脚本

e.g. sudo python filename.py

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM