我是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(在我的例子中我使用了&#39; *&#39;)我希望文件名自动完成?
2)如何在文件名中使用公式(在我的例子中是&#39;(n + 1)&#39;)?
非常感谢提前!
答案 0 :(得分: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')
答案 1 :(得分:0)
您可以使用glob模块进行*
扩展:
import glob
old = next(glob.glob('a_i={}_*'.format(n)))
actual = next(glob.glob('a_i={}_*'.format(n + 1)))
答案 2 :(得分:0)
我找到了一种方法来解决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转换为字符串以便连接 感谢您的输入!