AndrewC10
AndrewC10

Reputation: 357

Python - Copying Multiple Files Within Directory

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 

Upvotes: 1

Views: 2494

Answers (1)

falsetru
falsetru

Reputation: 368944

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)

Upvotes: 2

Related Questions