簡體   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