for j in os.system("ls *.out") 不迭代。根据扩展名更改文件名

问题描述 投票:0回答:1

我正在尝试编写一个脚本,该脚本将帮助我多次运行模型,更改输入文件的一个值的输入。该模型会覆盖输出文件,因此我需要使用额外的规范重命名输出以保留它们。

到目前为止我有这个:

import os
with open ('input.in', "r") as file:
    string=file.readlines()
ln = 48  # line to change 
inival = 60  # inicial value for the variable 
totval = 12   # total of values to run 
incr = 5     # incremental 
modvar = 'varname'
for i in range(0, totval-1):
   newinput = []
   val = inival+i*incr  #current new value 
   for j in range(0,ln-1):
      newinput.append(string[j])
   newinput.append(str(val) + str(string[ln].split('\t')[1:])) 
   for j in range(ln+1,len(string)):
      newinput.append(string[j])
   with open('input.in', 'w') as f:
        for i in newinput:
            f.write('%20s'%(i))
        
   print('file changed new =', val)

直到这里一切正常,现在解决我的问题:

    ./runmodel     #here I am not sure how to call the executable 
    
    
    for j in os.system("ls *.out")   # all output files have the .out extension
       os.rename( j, modvar+srt(val)"_"+j)

我想要的是每次模拟大约 10 个文件的 varname60_outputname.out。并且不要更改其他文件的名称。

当我测试最后两行时,我收到此错误:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Cell In[53], line 3

----> 3 for j in os.system("ls *.out"):
      4     os.rename( j,  modvar+srt(val)"_"+j)

TypeError: 'int' object is not iterable

我尝试过使用其他函数并使用 bash(mv) 但我无法设法将其放入名称具有变量的 for 循环中。 谢谢你

python bash os.system
1个回答
0
投票
for j in os.system("ls *.out")   # all output files have the .out extension
   os.rename( j, modvar+srt(val)"_"+j)

os.system
返回整数,您可以使用
glob.glob
,它将为您提供匹配模式的文件名列表,例如,如果我在每个
*.out
文件前面添加
old_
,我可以通过

做到这一点
import glob
import os
for filename in glob.glob("*.out"):
    os.rename(filename, "old_" + filename)
© www.soinside.com 2019 - 2024. All rights reserved.