You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python如何通过嵌套列表索引值作为文件名批量打开文件

解决方案

你给出的示例写法1 = open("1.txt", "r")属于Python非法语法,Python不允许使用纯数字作为变量名,推荐使用列表存储打开的文件对象,通过索引访问对应文件。

推荐实现代码

优先使用with上下文管理器实现,会自动管理文件生命周期,无需手动关闭文件,避免资源泄露:

from itertools import product

# 简化组合生成代码,无需循环append
comblist = list(product([1, 2], repeat=8))

# 遍历每一组文件编号组合
for file_group in comblist:
    # 批量打开当前组合对应的8个文件
    with [open(f"{num}.txt", "r") for num in file_group] as files:
        # files为长度8的列表,对应组合里8个编号的文件对象
        # 示例:读取第一个文件的全部内容
        content_1 = files[0].read()
        # 示例:读取第二个文件的一行内容
        line_2 = files[1].readline()
        # 此处补充你自己的业务逻辑即可

可选写法说明

如果你需要给每个文件对象单独命名(而非通过索引访问),可以用元组解包的方式实现:

for (n1, n2, n3, n4, n5, n6, n7, n8) in comblist:
    with open(f"{n1}.txt", "r") as f1, \
         open(f"{n2}.txt", "r") as f2, \
         open(f"{n3}.txt", "r") as f3, \
         open(f"{n4}.txt", "r") as f4, \
         open(f"{n5}.txt", "r") as f5, \
         open(f"{n6}.txt", "r") as f6, \
         open(f"{n7}.txt", "r") as f7, \
         open(f"{n8}.txt", "r") as f8:
        # 此处直接使用f1到f8访问对应文件即可
        pass

如果你的场景不适合用with自动关闭文件,也可以手动管理文件生命周期,注意使用完成后必须手动关闭文件:

for file_group in comblist:
    files = []
    for num in file_group:
        files.append(open(f"{num}.txt", "r"))
    # 此处写你的业务逻辑
    # 业务逻辑执行完成后必须手动关闭所有文件
    for f in files:
        f.close()

内容的提问来源于stack exchange,提问作者Zac

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.11 10:39:03