[英]python3 - how to produce output files whose names are modifications of the input files names?
您好,我正在使用包含以下代碼的 python 腳本:
from Bio import SeqIO
# set input file, output file to write to
gbk_file = "bin.10.gbk"
tsv_file = "results.bin_10.tsv"
cluster_out = open(tsv_file, "w")
# Extract CLuster info. write to file
for seq_record in SeqIO.parse(gbk_file, "genbank"):
for seq_feat in seq_record.features:
if seq_feat.type == "protocluster":
cluster_number = seq_feat.qualifiers["protocluster_number"][0].replace(" ","_").replace(":","")
cluster_type = seq_feat.qualifiers["product"][0]
cluster_out.write("#"+cluster_number+"\tCluster Type:"+cluster_type+"\n")
問題是我想將此腳本自動化到某個目錄中的多個文件,這樣我希望gbk_file
存儲所有以 .gbk 為后綴的文件,並且tsv_file
根據每個輸入文件生成一個相應的 output 文件.
因此,如果輸入文件的名稱為“bin.10.gbk”,則 output 將為“results.bin_10.tsv”。
我嘗試使用 glob python function 但不知道如何創建一個tsv_file
變量來存儲來自輸入文件名的修改字符串:
import glob
# setting variables
gbk_files = glob.glob("*.gbk")
tsv_files = gbk_files.replace(".gbk",".results.tsv")
cluster_out = open(tsv_files, "w")
進行更改時,我收到以下錯誤:
AttributeError: 'list' object 沒有屬性 'replace'
那么我該如何處理呢?
謝謝閱讀:)
希望下面的function可以幫助到你。
def processfiles():
for file in glob.glob("*.gbk"):
names = file.split('.')
tsv_file = f'results.{names[-3]}_{names[-2]}.tsv'
with open(tsv_file, 'w') as tsv:
tsv.write('write your content here')
tsv.close
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.