【发布时间】:2016-02-19 17:10:50
【问题描述】:
我有一个包含大量文件的目录,我想根据部分文件名将这些文件移动到文件夹中。我的文件列表如下所示:
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、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),它们对应于我的文件名的第三部分。我可以从这些名称中的每一个在我当前的工作目录中创建一组目录。在以下脚本之后是否有更好的方法来执行此操作,例如遍历物种列表,匹配文件,然后将其移动到正确的目录中?谢谢。
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))
【问题讨论】:
-
您希望文件保留其名称,还是应该删除
_species*?