0

I have a script which creates a file, but I want to see if that file exists so I can move it to a different directory. The problem I am getting is that it looks in one directory level too high.

Ex fileIn = a/b/c/d Its looking in d, not c

    print directory + "   go up one!!!"
    os.path.dirname(os.path.dirname(directory)) # this specific line does nothing
    if f.endswith("_edited.xml"):
        print "true"
    else:
        print "false"
        #shutil.copy2(f, aEdit)
1
  • Hows the variable directory set?
    – sgrg
    Commented Oct 12, 2015 at 19:16

3 Answers 3

6

If you use os.getcwd(), you can see what directory you are currently working in.

You want to use os.chdir(PATH) to change your directory.

The way to change directories is by using ..

>>> print(os.getcwd())
C:\Python34
>>> os.chdir('..')
>>> print(os.getcwd())
C:\
2

You can use os.path.isfile to check if the file exists. If so, keep stepping up the directory structure until you hit the root directory, then raise an error. Once the file doesn't exist in the directory, copy it there.

Finally, reset the directory back to its initial state.

import os

cd = os.getcwd()
while os.path.isfile(filename):
    os.chdir('..')  # go one level up.
    if len(os.getcwd) == 1:
        raise ValueError('Root recursion reached.')

# Save file.
shutil.copy2(filename, os.getcwd())

# Reset directory.
os.chdir(cd)
0
1
os.path.dirname(os.path.dirname(directory)) # this specific line does nothing

That line seems to "do nothing" because you are not storing the result anywhere. I'm not sure what your code should do (I have not understood your question very well), so I cannot advise a solution, however I guess that's your problem.

Not the answer you're looking for? Browse other questions tagged or ask your own question.