繁体   English   中英

重命名多个目录中的文件

[英]Rename files in multiple directories

我在多个目录中具有相同的文件名。 我想更改它们的名称,因此它们将对应于它们所在目录的唯一ID。

“ *”代表唯一标识符,例如“ 067”

文件名始终为“ NoAdapter_len25.truncated_sorted.fastq”

我希望每个目录中的文件名是“ * NoAdapter_len25.truncated_sorted.fastq”,其中*表示唯一标识符

这是我得到的错误:

Traceback (most recent call last):
  File "change_names.py", line 19, in <module>
    rename(name, new_name)
TypeError: Can't convert '_io.TextIOWrapper' object to str implicitly

这是产生它的代码:

from glob import glob
import re
from os import rename

#path = "/home/users/screening/results_Sample_*_hg38_hg19/N*"

files = glob(path)


for f in files:
    with open(f) as name:
        sample_id = f.partition('results_')[-1].rpartition('hg38_hg19')[0]
        #print(sample_id)
        back = f[-38:]
        new_name = sample_id + back
        rename(name, new_name)

您有一些问题:

  1. 您没有明显的理由打开文件(它确认文件存在并且可以在open时读取,但是即使打开了句柄,该名称也可以在该文件和rename之间移动或删除,因此您不会阻止任何操作。比赛条件)
  2. 您要将打开的文件对象传递给os.rename ,但是os.rename接受str ,而不是类似文件的对象
  3. 您正在对路径进行很多“魔术”操作,而不是使用适当的os.path函数

尝试这样做以简化代码。 在执行示例操作时,我包括了一些内联注释,但这没有多大意义(或者格式不佳):

for path in files:  # path, not f; f is usually placeholder for file-like object
    filedir, filename = os.path.split(path)
    parentdir = os.path.dirname(filedir)
    # Strip parentdir name to get 'Sample_*_' per provided code; is this what you wanted?
    # Question text seems like you only wanted the '*' part.
    sample_id = parentdir.replace('results_', '').replace('hg38_hg19', '')
    # Large magic numbers are code smell; if the name is a fixed name,
    # just use it directly as a string literal
    # If the name should be "whatever the file is named", use filename unsliced
    # If you absolutely need a fixed length (to allow reruns or something)
    # you might do keepnamelen = len('NoAdapter_len25.truncated_sorted.fastq')
    # outside the loop, and do f[-keepnamelen:] inside the loop so it's not
    # just a largish magic number
    back = filename[-38:]
    new_name = sample_id + back
    new_path = os.path.join(filedir, new_name)
    rename(path, new_path)

您提供了一个文件重命名( name )和一个文件名,它需要两个文件名。 要从文件获取文件名,可以执行此操作

old_filename = os.path.abspath(name.name)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM