我有几个文件存储在名为 controlFiles 的文件夹中。该文件夹的路径是Users/Desktop/myproject/controlFiles。
我正在尝试使用以下代码在 python 脚本中运行子进程命令:
def codeml(codeml_location, control_location):
runPath = codeml_location + '/codeml'
for file in os.listdir(control_location):
ctlPath = os.path.abspath(file)
subprocess.call([runPath, ctlPath])
该脚本的功能是运行一个名为 codeml 的命令行工具,第一个参数是 codeml 可执行文件的位置,第二个参数是 codeml 使用的控制文件的文件夹。当我运行此脚本时,codeml 运行,但出现错误:
error when opening file /Users/Desktop/myproject/subtree.39.tre.ctl
tell me the full path-name of the file?
我的困惑来自于这样一个事实:controlFiles 文件夹不在该路径中,但它仍然标识该文件夹中的文件。
为了检查我是否输入了正确的 control_location 参数,我编辑了代码:
def codeml(codeml_location, control_location):
runPath = codeml_location + '/codeml'
for file in os.listdir(control_location):
print os.path.abspath(file)
运行此命令会打印 controlFiles 文件夹中的所有文件,但同样不会在路径中显示该文件夹。以下是打印输出的示例:
/Users/Desktop/myproject/subtree.68.tre.ctl
/Users/Desktop/myproject/subtree.69.tre.ctl
/Users/Desktop/myproject/subtree.70.tre.ctl
/Users/Desktop/myproject/subtree.71.tre.ctl
要运行该函数,我的控制位置参数是:
control_location = /Users/Desktop/myproject/controlFiles
最后一点是,我在终端中的工作目录是/Users/Desktop/myproject,这是因为这是我的 Click 项目的位置。为什么会拾取文件而不是包含它们的文件夹?
最佳答案
os.listdir
确实列出了 control_location
目录中的文件名,而不是当前工作路径中的文件名。因此,您必须将文件名与路径control_location
连接起来:
for file in os.listdir(control_location):
ctlPath = os.path.abspath(os.path.join(control_location, file))
关于Python:绝对路径问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38130778/