我有一个目录,其中包含大量文件,我想根据文件名的一部分将其移动到文件夹中。我的文件列表如下:
ID1_geneabc_species1.fa
ID1_genesy_species1.fa
ID2峎geneabc_species1.fa
ID3基因abc_species2.fa
ID3_genesy_species2.fa
ID4\u genexy_species3.fa
我想根据文件名的最后一部分(species1,species2,species3)将我拥有的文件移动到单独的文件夹中。文件名的前半部分并不总是具有相同数量的数字和/或字母,而是始终由下划线“”分隔的3个部分组成。在
这是我在网上查找时尝试过的方法,但不起作用:
import os
import glob
dirs = glob.glob('*_*')
files = glob.glob('*.fa')
for file in files:
name = os.path.splitext(file)[0]
matchdir = next(x for x in dirs if name == x.rsplit('_')[0])
os.rename(file, os.path.join(matchdir, file))
我在下面脚本的列表中有一个名称列表(species1,species2,species3),它对应于我文件名的第三部分。我可以在当前工作目录中从这些名称中创建一组目录。在下面的脚本之后,是否有更好的方法来完成这项工作,比如在物种列表中循环,匹配文件,然后将其移动到正确的目录中?谢谢。在
^{pr2}$
所以,您需要一个函数,它从文件中获取文件夹名。然后迭代文件,创建不存在的dir并将文件移动到那里。这样的事情应该会解决的。在
相关问题 更多 >
编程相关推荐