Move files from one directory to another if they appear in a text file in Python (take 2)
Question: Ok I'm going to try this again, apologies for my poor effort in my pervious
question.

I am writing a program in Java and I wanted to move some files from one
directory to another based on whether they appear in a list. I could do it
manually but there a thousands of files in the directory so it would be an
arduous task and I need to repeat it several times! I tried to do it in Java
but because I am using Java it appears I cannot use java.nio, and I am not
allowed to use external libraries.

So I have tried to write something in python.

    
    
    import os
    import shutil
    
    with open('files.txt', 'r') as f:
        myNames = [line.strip() for line in f]
        print myNames
    
    dir_src = "trainfile"
    dir_dst = "train" 
    for file in os.listdir(dir_src):
        print file  # testing
        src_file = os.path.join(dir_src, file)
        dst_file = os.path.join(dir_dst, file)
        shutil.move(src_file, dst_file)
    

"files.txt" is in the format:

    
    
    a.txt
    edfs.txt
    fdgdsf.txt
    

and so on.

So at the moment it is moving everything from train to `trainfile`, but I need
to only move files if the are in the `myNames` list.

Does anyone have any suggestions?


Answer: > so at the moment it is moving everything from train to trainfile, but ii
> need to only move files if the are in the myName list

You can translate that "if they are in the myName list" directly from English
to Python:

    
    
    if file in myNames:
        shutil.move(src_file, dst_file)
    

And that's it.

However, you probably want a _set_ of names, rather than a _list_. It makes
more conceptual sense. It's also more efficient, although the speed of looking
things up in a list will probably be negligible compared to the cost of
copying files around. Anyway, to do that, you need to change one more line:

    
    
    myNames = {line.strip() for line in f}
    

And then you're done.

