gpt4 book ai didi

python - os.walk 中返回的 "root"变量中的完整路径名

转载 作者:行者123 更新时间:2023-12-01 05:06:38 25 4
gpt4 key购买 nike

我正在使用 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++ 代码示例。

最佳答案

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

关于python - os.walk 中返回的 "root"变量中的完整路径名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24871147/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com