Anekdotin
Anekdotin

Reputation: 1591

Move up one directory to check if file exists

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)

Upvotes: 0

Views: 1655

Answers (3)

Alexander
Alexander

Reputation: 109528

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)

Upvotes: 2

Andrea Corbellini
Andrea Corbellini

Reputation: 17751

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.

Upvotes: 1

Programmer
Programmer

Reputation: 293

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:\

Upvotes: 6

Related Questions