Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/shell/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
通过Python使用文件名中的变量运行shell命令_Python_Shell - Fatal编程技术网

通过Python使用文件名中的变量运行shell命令

通过Python使用文件名中的变量运行shell命令,python,shell,Python,Shell,我有命名约定的文件 st009_out.abc1.dat st009_out.abc2.dat st009_out.abc3.dat .................. .................. 我正在编写Python代码,希望使用文件中的数据执行数学函数,并需要从文件中提取第二列。我试过这样做: for k in range(1,10): file1=open('st009_out.abc'+str(k)+'.dat','r') ...........

我有命名约定的文件

st009_out.abc1.dat
st009_out.abc2.dat
st009_out.abc3.dat 
..................
..................
我正在编写Python代码,希望使用文件中的数据执行数学函数,并需要从文件中提取第二列。我试过这样做:

for k in range(1,10):
    file1=open('st009_out.abc'+str(k)+'.dat','r')
    ...........
    os.system("awk '{print $2}' st009_out.abc${k}.pmf > raj.dat")
但这不起作用,因为它没有在shell命令中获取
k
的值

我如何进步?

试试看

os.system("awk '{print $2}' st009_out.abc"+str(k)+".pmf > raj.dat")
试一试


您使用文件名两次,因此只设置一次

for k in range(1,10):
    name = 'st009_out.abc'+str(k)+'.dat'
    file1=open(name,'r')
    ...........
    os.system("awk '{print $2}' " + name  + " > raj.dat")

或者最好在python中重写awk

您使用两次文件名,所以只设置一次

for k in range(1,10):
    name = 'st009_out.abc'+str(k)+'.dat'
    file1=open(name,'r')
    ...........
    os.system("awk '{print $2}' " + name  + " > raj.dat")

或者最好用python重写awk

@rajitha:另外,python中的函数与本例中的
awk
完全相同。谢谢。我之前使用split函数得到了它,因为我一直在尝试用python中的shell命令,但现在遇到了问题。再次感谢您的帮助。@rajitha:另外,Python中的函数与本例中的
awk
完全相同。谢谢。我之前使用split函数得到了它,因为我一直在尝试使用Python中的shell命令,但现在遇到了问题。再次感谢你的帮助。