1

我正在使用 os.walk 运行目录树检查某些输入文件,然后在有正确输入的情况下运行程序。我注意到我遇到了问题,因为 os.walk 正在评估循环中的根变量:

for root, dirs, files in os.walk('.'):# I use '.' because I want the walk to 
                                      # start where I run the script. And it 
                                      # will/can change
    if "input.file" in files:
         infile = os.path.join(root,"input.file")
         subprocess.check_output("myprog input.file", Shell=True)
                                      # if an input file is found, store the path to it 
                                      # and run the program

这给了我一个问题,因为 infile 字符串看起来像这样

  ./path/to/input.file 

当它需要看起来像这样以便程序能够找到它时

 /home/start/of/walk/path/to/input.file

我想知道是否有更好的方法/不同的方式来使用 os.walk 以便我可以随意保留起始目录,但仍然可以使用它为我找到的任何文件的完整路径。谢谢

我正在使用的程序是我用 c++ 编写的,我想我也可以修改它。但我不是在问如何在这个问题中做到这一点,只是为了澄清这个问题是关于 python 的 os.walk 和相关主题,这就是为什么这里没有我的 c++ 代码示例。

4

1 回答 1

2

而不是 using .,而是通过 using 将其转换为绝对路径os.path.abspath(".")。这将在您开始之前将您的当前路径转换为绝对路径。

于 2014-07-21T17:31:57.077 回答