Ovisek
Ovisek

Reputation: 143

using walk function in python

I am dealing with a folder hierarchy like the following:

c:/users/rox/halogen/iodine/(some .txt files)
c:/users/rox/halogen/chlorine/(some .txt files)
c:/users/rox/inert/helium/(some .txt files)
c:/users/rox/inert/argon/(some .txt files)

now I was iterating through out the folder by using os.walk and processing the files.
But the problem is if I want to generate analysis output to the folder 'halogen' after analyzing all sub-folders under halogen then what should I do... I was using:

for root,dirs,files in os.walk(path,'*.txt):
    .....
    .......[processing file]
    out.write(.....)    # writing output in the folder which we are analyzing

but how to write the output to a folder that lies two-step back(i.e halogen or inert)..

Upvotes: 1

Views: 820

Answers (2)

Andrew Clark
Andrew Clark

Reputation: 208585

You can open your output file using a relative path from the directory you are processing like this:

for root, dirs, files in os.walk(path, '*.txt'):
    out = open(os.path.join(root, '..', '..'), 'a')
    out.write(...)

Upvotes: 0

pyfunc
pyfunc

Reputation: 66729

Open your output file prior to the walk.

out = open(os.path.join(path, outputfilename), 'w')

and then walk the path for processing your inputs

for root,dirs,files in os.walk(path,'*.txt):
    .....
    out.write(..)

This way you already know the root path. Else, if you are sure that your path is just two steps back.

os.path.join(current_path, '..', '..')

will give you folder path, two step backwards

Upvotes: 2

Related Questions