Ajay
Ajay

Reputation: 407

full path name in the "root" variable returned in os.walk

I am using os.walk to run through a tree of directories check for some input files and then run a program if the proper inputs are there. I notice I am having a problem because of the away that os.walk is evaluating the root variable in the loop:

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

This is giving me an issue because the infile string looks like this

  ./path/to/input.file 

When it needs to look like this for the program to be able to find it

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

I want to know if there is a better method/ a different way to use os.walk such that I can leave the starting directory arbitrary, but still be able to use the full path to any files that it finds for me. Thanks

The program I am using is written by me in c++ and I suppose I could modify it as well. But I am not asking about how to do that in this question just to clarify this question is about python's os.walk and related topics that is why there is no examples of my c++ code here.

Upvotes: 1

Views: 630

Answers (1)

TheSoundDefense
TheSoundDefense

Reputation: 6945

Instead of using ., convert it to the absolute path by using os.path.abspath("."). That will convert your current path to an absolute path before you begin.

Upvotes: 2

Related Questions