1

I am new to Python and attempting to write an automated testing program. More specifically, I am trying to copy several .xlsx files from one directory to another. I've researched pretty thoroughly and am partially there. My code is below, which does not return and errors, but does not accomplish what I am trying to do. I believe my code is not granular enough (I am getting stuck at the directory level). In a nutshell: File A contains c, d, e, f.1, f.2, f.3 (all Excel docs). File B is empty. I am trying to copy f.1, f.2, and f.3 into File B. I believe I need to add the startswith function at some point, too. Any help is appreciated. Thanks!

import os
import shutil
import glob

source = 'C:/Users/acars/Desktop/a'
dest1 = 'C:/Users/acars/Desktop/b'

src_files = os.listdir('C:/Users/acars/Desktop/a')

for file_name in src_files:
    full_file_name = os.path.join('C:/Users/acars/Desktop/a','a') #'a' incorrect
    if (os.path.isfile(full_file_name)):
        shutil.copy(full_file_name, dest1)
    else:
        break 

1 Answer 1

2

Use the variables source and dest1:

source = 'C:/Users/acars/Desktop/a'
dest1 = 'C:/Users/acars/Desktop/b'

src_files = os.listdir(source)

for file_name in src_files:
    if not file_name.startswith('f'):
        continue
    src = os.path.join(source, file_name)  # <--
    dst = os.path.join(dest1, file_name)   # <--
    shutil.copy(src, dst)
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you. That copied all of the files. I would like to just copy the ones beginning with 'f' and will eventually rename them in the destination file.
I'm assuming I need an if statement specifying the startswith
@AndrewC10, I updated the code in the answer to skip files whose name does not starts with f.

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.