如何使用Python处理NCBI FTP路径,生成带_genomic.fna.gz后缀的目标路径
NCBI FTP基因组文件路径转换Python实现
实现逻辑
- 先对输入的原始路径做标准化处理,去除末尾多余斜杠,兼容不同格式的输入
- 提取路径最后一级目录名称
- 按照规则拼接目标文件名,再追加到原路径后得到最终结果
代码实现
推荐用Python标准库urllib处理,兼容性更强,可适配各类FTP路径格式:
from urllib.parse import urlparse, urlunparse def convert_ncbi_ftp_path(origin_path: str) -> str: # 解析FTP路径结构 parsed = urlparse(origin_path) # 标准化路径,去除末尾多余斜杠 clean_path = parsed.path.rstrip('/') # 提取最后一级目录名 last_dir = clean_path.split('/')[-1] # 生成目标文件名 target_filename = f"{last_dir}_genomic.fna.gz" # 拼接新路径并重构完整URL new_path = f"{clean_path}/{target_filename}" return urlunparse(parsed._replace(path=new_path))
如果仅处理固定格式的NCBI路径,也可以用更简洁的字符串处理方案:
def convert_ncbi_ftp_path_simple(origin_path: str) -> str: clean_path = origin_path.rstrip('/') last_dir = clean_path.split('/')[-1] return f"{clean_path}/{last_dir}_genomic.fna.gz"
测试示例
origin_path = "ftp://ftp.ncbi.nlm.nih.gov/genomes/all/GCA/001/316/945/GCA_001316945.3_ASM131694v3" print(convert_ncbi_ftp_path(origin_path)) # 输出:ftp://ftp.ncbi.nlm.nih.gov/genomes/all/GCA/001/316/945/GCA_001316945.3_ASM131694v3/GCA_001316945.3_ASM131694v3_genomic.fna.gz
两种实现都兼容原始路径末尾带斜杠的输入场景。
内容的提问来源于stack exchange,提问作者Yad.yos
相关产品推荐
相关产品推荐

