2016-02-19 87 views
2

我有一個包含大量文件的目錄,我想根據部分文件名移動到文件夾中。我的文件列表如下:python:我可以根據名稱的一部分移動一個文件到一個名稱爲該文件夾的文件夾

  • 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)) 
+0

你想讓這些文件保留它們的名字嗎?或者'_species *'被刪除? – zondo

+0

沒關係。 –

回答

0

所以,你需要一個函數,它從文件中獲取文件夾名稱。然後你遍歷文件,創建不存在的dirs並在那裏移動文件。像這樣的東西應該解決。

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) 
+0

反正你正在使用'os';你爲什麼不使用'os.path.join()'? – zondo

+0

這正是我正在尋找的!謝謝。 –

+0

您可以通過腳本的第一部分來引導我嗎?我想了解如何定義文件名的不同部分以供將來使用(即根據文件名的部分連接文件)。我大部分只是在這一行丟失:返回文件名[pos1 + 1:pos2]。謝謝。 –

相關問題