Python 自动完成变量名称

Python Autocomplete Variable Name

我是 Python 的新手,想要一个 while 循环内的自动完成变量。我试着举一个最小的例子。假设我的文件夹中有以下文件,每个文件都以相同的字母和递增的数字开头,但文件名的末尾仅包含随机数字

a_i=1_404
a_i=2_383
a_i=3_180

我想要一个类似

的while循环
while 1 <= 3:
    old_timestep     = 'a_i=n_*'
    actual_timestep  = 'a_i=(n+1)_*' 
    ... (some functions that need the filenames saved in the two above initialised variables)
    n = n+1

因此,如果我开始循环,我希望它自动处理我目录中的所有文件。结果有两个问题:

1) 我如何告诉 python 我希望文件名自动完成(在我的示例中我使用了“*”)?

2) 如何在文件名中使用公式(在我的示例中为“(n+1)”)?

非常感谢!

1) 据我所知,您不能自动执行此操作。我会将所有文件名存储在列表中的目录中,然后通过该列表进行搜索

from os import listdir
from os.path import isfile, join
dir_files = [ f for f in listdir('.') if isfile(join('.',f)) ]
while i <= 3:
    old_timestep = "a_i=n_"
    for f in dir_files:
        if f.startswith(old_timestep):
            # process file
    i += 1

2) 可以使用字符串连接

f = open("a_i=" + str(n + 1) + "remainder of filename", 'w')

您可以使用glob模块进行*扩展:

import glob
old = next(glob.glob('a_i={}_*'.format(n)))
actual = next(glob.glob('a_i={}_*'.format(n + 1)))

我找到了解决 1) 的方法,方法是首先执行 a) 然后执行 b):

1) a) 截断文件名以便只保留前 x 个字符:

for i in {1..3}; do
    cp a_i=$((i))_* a_i=$((i))
done

b)

n = 1
while n <= 3:
    old = 'a_i=' + str(n) 
    new = 'a_i=' + str(n+1)

str() 用于将整数 n 转换为字符串以便连接 感谢您的输入!