![](/img/trans.png)
[英]Copy template file to multiple directories, query template files for rename based on directory
[英]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)
您有一些問題:
open
時讀取,但是即使打開了句柄,該名稱也可以在該文件和rename
之間移動或刪除,因此您不會阻止任何操作。比賽條件) os.rename
,但是os.rename
接受str
,而不是類似文件的對象 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.