Eugene B
Eugene B

Reputation: 1013

Copy a file with a certain string in the filename in python

I need to copy a file that contains some string, call it mystring, in the filename from a directory to another. At the moment I use

for file in glob.glob(FileNameM):
        shutil.copy(file, dest);

where dest is the destination directory and

FileNameM = source_directory + some_known_string + mystring + "*"

This code works fine when there is an extension only after mystring, but if there is something else plus an extension the code fails.

Example FileNameM that works:

/home/eugene/GDrive/Project-related/Skyrmion_Lattice_Output/Output_Good_Enough/Parameters__triangular_N_225_kappa_1.0_beta_0.11_a_3.63311050137*

and leads to the file

/home/eugene/GDrive/Project-related/Skyrmion_Lattice_Output/Output_Good_Enough/Parameters__triangular_N_225_kappa_1.0_beta_0.11_a_3.63311050137.dat

Example FileNameM that doesn't work:

/home/eugene/GDrive/Project-related/Skyrmion_Lattice_Output/Output/Parameters__triangular_N_225_kappa_1.0_beta_0.12_a_3.6341634222*

and this shall lead to the file

/home/eugene/GDrive/Project-related/Skyrmion_Lattice_Output/Output/Parameters__triangular_N_225_kappa_1.0_beta_0.12_a_3.63416342223.dat

Do you have any idea how can I improve?

Upvotes: 1

Views: 1519

Answers (1)

arx5
arx5

Reputation: 336

I just tried it with your example filenames and got both filenames by glob.glob(), even with more characters missing:

import glob
    FileNameM = 'test\Parameters__triangular_N_225_kappa_1.0_beta_0.12_a_3.6341634*'
    for file in glob.glob(FileNameM):
        print(file)
# test\Parameters__triangular_N_225_kappa_1.0_beta_0.12_a_3.63416342223.dat

Running on Windows; a dummy file was in the subfolder test next to the script.

Upvotes: 2

Related Questions