Search code examples
pythonlinuxsshmobaxterm

Use python with mobaxterm to copy 25 random files from one folder to another


I'm trying to write a python script that I can run using mobaxterm to grab 25 random files from a folder and copy them to another folder.

I am very new to using mobaxterm, my internship has been mostly writing small scripts to help my coworkers automate daily stuff, so any advice is appreciated! I can open mobaxterm and navigate to the folder where this python script is held but I get these errors:

IOError: [Errno 21] Is a directory: 

my code right now is as follows

import shutil, random, os

dirpath = '/SSH_folder_where_stuff_is/images/' 

destDirectory = '/SSH_folder_where_stuff_should_go/'

filenames = random.sample(os.listdir(dirpath), 25)
for fname in filenames:
    srcpath = os.path.join(dirpath, fname)
    shutil.copyfile(srcpath, destDirectory)
    print('done!')

Thank you in advance for any suggestions!


Solution

  • You need to change your shutil usage. shutil takes two filenames, but in your code the second one is a directory.

    Here is a corrected version.

    import shutil, random, os
    
    dirpath = '/SSH_folder_where_stuff_is/images/' 
    destDirectory = '/SSH_folder_where_stuff_should_go/'
    
    filenames = random.sample(os.listdir(dirpath), 5)
    for fname in filenames:
        srcpath = os.path.join(dirpath, fname)
        # Change the second parameter here.
        shutil.copyfile(srcpath, destDirectory+fname)
        print('done!')