导读
用python os.rename函数把一组文件名改成另外一组文件名。
一、准备文件
metadata.txt => map file
rawdata/ => fastq file
二、python3代码
目的:num_FDSWxxxx-1r_1/2.fq => character_R1/2.fastq
思路:
1 读取map文件中的一三两列成字典
2 把文件名切割(re.split),修改文件名(os.rename)
#!/usr/bin/env python3
import os,sys,re
# 取metadata两列做成字典,第一列是raw id;第三列是new id
Dict = {}
with open("metadata.txt") as f:
for line in f:
line = line.strip()
cell = re.split(r'\t', line)
if cell[0] != "SampleID":
Dict[cell[0]] = []
Dict[cell[0]].append(cell[2])
# rename test
for each in os.listdir("rawdata"):
cell = re.split(r'_|\.', each)
if cell[2] == "1":
print("rawdata/{}_R1.fastq".format("".join(Dict[cell[0]])))
elif cell[2] == "2":
print("rawdata/{}_R2.fastq".format("".join(Dict[cell[0]])))
# rename
for each in os.listdir("rawdata"):
cell = re.split(r'_|\.', each)
if cell[2] == "1":
os.rename("rawdata/{}".format(each), "rawdata/{}_R1.fastq".format("".join(Dict[cell[0]])))
elif cell[2] == "2":
os.rename("rawdata/{}".format(each), "rawdata/{}_R2.fastq".format("".join(Dict[cell[0]])))
网友评论