如何用Python解析bencode获取.torrent生成的目录名?
获取Torrent文件生成的目录名(替代libtorrent方案)
问题根源
你触发的TypeError是因为错误地把info["name"](字符串类型)当成可迭代对象去遍历。根据BitTorrent元数据规范,info字段结构分两种场景:
- 单文件种子:
info里没有files字段,name对应单个文件名 - 多文件种子:
info包含files字段,name就是下载完成后生成的根目录名
原libtorrent的torrent_info.name()本质就是返回这个name字段,所以只需直接读取它即可。
正确实现代码
import bencode def get_torrent_directory_name(torrent_path): with open(torrent_path, "rb") as fin: torrent_data = bencode.bdecode(fin.read()) info = torrent_data.get("info", {}) # 对应libtorrent返回的目录/文件名:多文件是根目录,单文件是文件名 return info.get("name") # 测试使用 TORRENT_PATH = "path/to/your/torrent.torrent" print(get_torrent_directory_name(TORRENT_PATH))
补充:遍历所有文件路径(修正你的原有代码)
如果需要获取种子内的所有文件路径,要区分单文件和多文件场景,避免报错:
import bencode import itertools def get_torrent_all_files(torrent_path): with open(torrent_path, "rb") as fin: torrent_data = bencode.bdecode(fin.read()) info = torrent_data.get("info", {}) if "files" in info: # 多文件种子,拼接每个文件的路径片段 return itertools.chain(*(f["path"] for f in info["files"])) else: # 单文件种子,直接返回文件名 return [info.get("name")] # 调用示例 for part in get_torrent_all_files(TORRENT_PATH): print(part)
内容的提问来源于stack exchange,提问作者weast
相关产品推荐
相关产品推荐

