2015-02-23 115 views
0

我是Python新手,想要在while循环中使用自动完成变量。我试着举一个最简单的例子。让我们假设我有我的文件夹中的以下文件,各自开始用相同的字母和越来越多的,但文件名末尾只是由随机数Python自动完成变量名称

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

我要像

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 
while循环

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

1)我如何告诉python(在我的例子中我使用了'*')我想要自动完成文件名?

2)如何使用文件名内的公式(在我的例子中'(n + 1)')?

非常感谢提前!

回答

0

我找到了一种方法,首先做一个解决1)我自己)然后b):

1)),以便只有所述第一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到字符串中的为了连接 感谢您的意见!

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') 
0

可以使用glob模块做*扩张做搜索:

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

我获得以下错误信息: “” “” 回溯(最后最近一次调用): 文件 “script.py” 34行,在 surf_sol_old =下一个(glob.glob('A_I = {} _ * '.format(o_timer))) ValueError:零长度字段名格式“”“” – Jan 2015-02-23 12:20:02

+0

使用更新版本的python – Arthur 2015-02-23 13:37:47