【问题标题】:python: can i move a file based on part of the name to a folder with that namepython:我可以将基于部分名称的文件移动到具有该名称的文件夹中吗
【发布时间】: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*

标签: python biopython


【解决方案1】:

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

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)

【讨论】:

  • 无论如何你都在使用os;为什么不使用os.path.join()
  • 这正是我想要的!谢谢。
  • 您可以带我看一下这个脚本的第一部分吗?我想了解如何定义文件名的不同部分以供将来使用(即基于文件名的部分连接文件)。我大多只是迷失在这一行:return filename[pos1+1:pos2]。谢谢。
  • pos1 是字符串中最右边的_ 的位置,pos2. 的位置,并在您使用切片的这两个字符之间取行。例如:s = "some_string.txt"pos1 此处等于 4,pos2 等于 11。然后您将子字符串 s[5:11] 从位置 5 开始,以排除 _ 并以位置 11 结束(已排除)。
猜你喜欢
  • 1970-01-01
  • 2016-02-21
  • 1970-01-01
  • 2023-03-17
  • 1970-01-01
  • 2021-08-02
  • 2017-06-07
  • 2020-05-03
  • 1970-01-01
相关资源
最近更新 更多