-1

Hi everyone I´m trying now to move some files from one folder to another. The files that i have are

  • results_1_1
  • results_2_1
  • results_3_1
  • results_1_2
  • results_2_2
  • results_3_2

What i´d like to get is to move files

  • results_1_1
  • results_2_1
  • results_3_1 to one folder let´s call it A

other

  • results_1_2
  • results_2_2
  • results_3_2 to another let´s call it B

I don´t want to do it manually because, in reality, I have much more files

I have created by python a new folder that I want to have

and so far about moving the files to another directory

import shutil
source_folder = r"C:/Users/...."
destination_folder= r"C:/Users/...."
files_to_move = ['results_1_3.dat']

for file in files_to_move:
    source = source_folder + file 
    destination = destination_folder + file 
    shutil.move(source,destination)
print("Moved!")

But with this program I can only move one file at a time I tried writing results_.+3.dat', results*_3.dat' but I´m seeing an error all the time

UglyBetty
  • 17
  • 1
  • I would use a for loop to place filenames into your `files_to_move` array, since it looks like the filenames increment by one. – veridis_quo_t Nov 04 '21 at 10:37

2 Answers2

0

You can use os.listdir to find all the files in your directory.

This code finds all the files which names end with '1'.

import os
files_to_move = [f for f in os.listdir() if f.split('.')[0][-1] == '1']

You can also add an extension check if necessary:

files_to_move = [f for f in os.listdir() if f.split('.')[0][-1] == '1' and f.split('.')[1] == 'dat']
0

You can list all files in your directory using os.listdir(source_folder)

If you have mixed files in your directory, you can select your results files with something like this

files_to_move = [x for x in os.listdir(source_folder) if all(j in x for j in ['results', '.dat'])]

I would then create a dictionary containing the destination folders associated with the numbers in your results file.

destination_A = r'/path/to/destinationA'
destination_B = r'/path/to/destinationB'

moving_dict = {
    '1': destination_A,
    '2': destination_B
}

You can then move your files based on the filename

for file in files_to_move:
    destination_folder = moving_dict[file[:-4].split('_')[-1]]
    source = source_folder + file 
    destination = destination_folder + file 
    shutil.move(source,destination)
Mitchell Olislagers
  • 1,758
  • 1
  • 4
  • 10