繁体   English   中英

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

[英]python: can i move a file based on part of the name to a folder with that name

我有一个包含大量文件的目录,我想根据文件名的一部分移入文件夹。 我的文件列表如下所示:

  • ID1_geneabc_species1.fa

  • ID1_genexy_species1.fa

  • ID2_geneabc_species1.fa

  • ID3_geneabc_species2.fa

  • ID3_genexy_species2.fa

  • ID4_genexy_species3.fa

我想根据文件名的最后一部分(species1,种类2,种类3)将拥有的文件移动到单独的文件夹中。 文件名的前半部分不一定总是具有相同的数字和/或字母,而是总是由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,种类2,种类3),这些名称与文件名的第三部分相对应。 我可以使用这些名称在当前工作目录中创建一组目录。 在以下脚本之后是否有更好的方法来执行此操作,例如遍历物种列表,匹配文件,然后将其移至正确的目录? 谢谢。

from Bio import SeqIO
import os
import itertools

#to get a list of all the species in genbank file
all_species = []
for seq_record in SeqIO.parse("sequence.gb", "genbank"):
    all_species.append(seq_record.annotations["organism"])

#get unique names and change from set to list
Unique_species = set(all_species)
Species = list(Unique_species)

#send to file
f = open('speciesnames.txt', 'w')
for names in Species:
    f.write(names+'\n')
f.close()

print ('There are ' + str(int(len(Species))) + ' species.')

#make directory for each species
path = os.path.dirname(os.path.abspath(__file__))
for item in itertools.product(Species):
    os.makedirs(os.path.join(path, *item))

因此,您需要一个从文件中获取文件夹名称的函数。 然后,您遍历文件,创建不存在的目录并将文件移到那里。 这样的东西应该可以解决。

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)

暂无
暂无

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

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