moving mutiple files from one folder to another using python
Question: I have a “.txt ”file which consists of various filenames and I want to search
each filename in a source_folder where these files are actually kept and I
want to move the matching files to a specific folder. Source_folder contain
files within multiple folders.

My .txt file looks like this:

    
    
    ant1.aiq
    ant2.aiq
    ant3.aiq
    ant4.aiq
    

I want to match each line of my textfile (`ant1.aiq`, `ant2.aiq` and so on)
with filenames which are present at some specific place (`R:\Sample`) and
extract matching files into some other place (`R:\sample\wsa`).

So far I have written following code but it doesnt work:

    
    
    import os
    import shutil
    
    sourceDir = "R:\test_vectors\pxi_wcdma"
    targetDir = "R:\\Sample\\wsa"
    existingFiles = set(f for f in os.listdir(sourceDir) if os.path.isfile(os.path.join(sourceDir, f)))
    infilepath = "aiq_hits.txt"
    with open(infilepath) as infile:
        for line in infile:
            fname = line.strip()
            if fname not in existingFiles: continue
                shutil.move(os.path.join(sourceDir, fname),os.path.join(targetDir, fname))
    

Path for source folder is : R:\test_vectors\pxi_wcdma pxi_wcdma folder
contains .aiq files which are to be copied


Answer: I've tested this on my server and it works. Make sure the paths are correct
and you've permissions to read and write.

    
    
    import os
    import shutil
    
    file = "test.txt"
    sourceDir = "R:\\test_vectors\\pxi_wcdma\\"
    targetDir = "R:\\Sample\\wsa\\"
    
    for line in open("test.txt") :
        line =  line.rstrip('\n')
        if os.path.isfile(sourceDir+line):
            shutil.move(sourceDir+line, targetDir+line)
    

* * *

Some tips about path names on windows OS:

This works both in linux and windows:

    
    
    'C:/mydir'
    

Other posibility is :

    
    
    'C:\\mydir'
    

If you have problems with some names you can also try raw strings:

    
    
    r'C:\mydir'
    

