python:我可以将基于部分名称的文件移动到具有该名称的文件夹中吗
我有一个包含大量文件的目录,我想根据部分文件名将这些文件移动到文件夹中。我的文件列表如下所示:python:我可以将基于部分名称的文件移动到具有该名称的文件夹中吗,python,biopython,Python,Biopython,我有一个包含大量文件的目录,我想根据部分文件名将这些文件移动到文件夹中。我的文件列表如下所示: 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)将我拥有的文件移动到单独的文件夹中。
- ID1_geneabc_species1.fa
- ID1_genexy_species1.fa
- ID2_geneabc_species1.fa
- ID3_geneabc_species2.fa
- ID3_genexy_species2.fa
- ID4_genexy_species3.fa
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))
所以,您需要一个函数,它从文件中获取文件夹名称。然后迭代文件,创建不存在的目录,并将文件移动到那里。这样的事情应该会解决的
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)
您希望文件保留其名称,还是应该删除
\u species*
?您仍在使用os
;为什么不使用os.path.join()
?这正是我想要的!谢谢。你能带我看一下这个剧本的第一部分吗?我想了解如何定义文件名的不同部分以供将来使用(即基于文件名的各个部分连接文件)。我对这一行几乎一无所知:returnfilename[pos1+1:pos2]。谢谢。pos1
是字符串中最右边的\
位置,pos2
是
位置,并在这两个字符之间使用切片。例如:s=“some_string.txt”
,pos1
这里等于4,而pos2
等于11。然后取子字符串s[5:11]
,从位置5开始,以排除\uu
并以位置11(已排除)结束。