3

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?

8
  • Did you get my question? @Marcus.Aurelianus Commented Jul 11, 2018 at 8:19
  • Are you running this on Linux? Commented Jul 11, 2018 at 8:20
  • 1
    Windows 10, no not linux Commented Jul 11, 2018 at 8:21
  • Either run the script with sudo or from a shell that was started 'as administrator'? Commented Jul 11, 2018 at 8:21
  • 1
    no, it says no such files. Although there is a file @jc1850 Commented Jul 11, 2018 at 9:19

3 Answers 3

2

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)
Sign up to request clarification or add additional context in comments.

Comments

0

You need to run your python script as sudo user

e.g. sudo python filename.py

1 Comment

sudo does not exist in windows
0

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

6 Comments

Is ./data/f_1 a destination or a file to be copied?
The files from the folder
The root folder has more directories. The code needs to check each folder and find the file
Does the traceback say anything else like which line is causing the error?
Thought it might not, so for some reason you dont have permission to do something to the file, do you know which line is causing the issue? Is it the os.walk(my_path) call?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.