python:我可以根据文件名的一部分将文件移动到具有该名称的文件夹中吗

2024-10-05 13:14:12 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个目录,其中包含大量文件,我想根据文件名的一部分将其移动到文件夹中。我的文件列表如下:

  • 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}$

Tags: 文件目录文件夹列表os文件名globfile
1条回答
网友
1楼 · 发布于 2024-10-05 13:14:12

所以,您需要一个函数,它从文件中获取文件夹名。然后迭代文件,创建不存在的dir并将文件移动到那里。这样的事情应该会解决的。在

def get_dir_name(filename):
    pos1 = filename.rfind('_')
    pos2 = filename.find('.')
    return filename[pos1+1:pos2]

for f in glob.glob('*.fa'):
    cwd = os.getcwd()
    dir_name = cwd+'/'+get_dir_name(f)
    print dir_name
    if not os.path.exists(dir_name):
        os.mkdir(dir_name)
    os.rename(f, dir_name+'/'+f)

相关问题 更多 >

    热门问题