Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 589
TheTechGuy Avatar asked Apr 19 '26 21:04

TheTechGuy


1 Answers

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)
like image 145
TheTechGuy Avatar answered Apr 21 '26 10:04

TheTechGuy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!