简体   繁体   English

复制python中文件名中具有特定字符串的文件

[英]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. 我需要将文件名中包含某个字符串的文件mystring从一个目录复制到另一个目录。 At the moment I use 目前我使用

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

where dest is the destination directory and 其中dest是目标目录,并且

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. 仅在mystring后面有扩展名时,此代码才能正常工作,但如果还有其他扩展名,则该代码将失败。

Example FileNameM that works: 有效的示例FileNameM

/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: 示例FileNameM不起作用:

/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? 您知道我该如何改善吗?

I just tried it with your example filenames and got both filenames by glob.glob() , even with more characters missing: 我只是用您的示例文件名进行了尝试,并通过glob.glob()获得了两个文件名,即使缺少更多字符:

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; 在Windows上运行; a dummy file was in the subfolder test next to the script. 脚本旁边的子文件夹test有一个伪文件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM