Abdulla Salimov
Abdulla Salimov

Reputation: 149

Python - copy specific file from subfolder to destination, get filename from text file

I want to get my script to read a list of names from a list(txt), then search for those in a selected folder with subfolders, then copy and paste those files to another selected folder. My script running without error but no result.

My script:

import os
import os.path
import shutil

textFile = ("D:\\Test\\list.txt")
sourceFolder = ("D:\\Test")
destinationFolder = ("D:\\")

filesToFind = []
with open(textFile, "r") as tx:
    for row in tx:
        filesToFind.append(row.strip())

for root, dirs, filename in os.walk(sourceFolder):
    if filename in filesToFind:
        f = os.path.join(root, filename)
        shutil.copy(f, destinationFolder)

Upvotes: 3

Views: 395

Answers (2)

NehaJadhav
NehaJadhav

Reputation: 21

# Same code using glob #
## More efficient and also tested one ##
## One more feature added- checks file name given present or not ##

    import os
    import os.path
    import shutil
    import glob

    textFile = ("D:\\Test\\list.txt")
    sourceFolder = ("D:\Test")
    destinationFolder = ("D:\\")

    f = open(textFile, "r").readlines()
    for i in f:
        ListFile= glob.glob(os.path.join(sourceFolder,"**",i.strip()),recursive=True)
        if len(ListFile):
            print(ListFile[0],destinationFolder,os.path.basename(ListFile[0]))
            destinationfile=os.path.join(destinationFolder,os.path.basename(ListFile[0]))
            shutil.copyfile(ListFile[0],destinationfile)
        else:
            print(i,"-File not found")

Upvotes: 2

Haven’t test it but I think this will work - change this:

for root, dirs, filename in os.walk(sourceFolder):
    if filename in filesToFind:
        f = os.path.join(root, filename)
        shutil.copy(f, destinationFolder)

To this:

for root, dirs, filenames in os.walk(sourceFolder):
    for filename in filenames:
        if filename in filesToFind:
            f = os.path.join(root, filename)
            shutil.copy(f, destinationFolder)

Upvotes: 2

Related Questions