Search code examples
pythonwindowsos.path

Open File in Another Directory (Python)


I've always been sort of confused on the subject of directory traversal in Python, and have a situation I'm curious about: I have a file that I want to access in a directory essentially parallel to the one I'm currently in. Given this directory structure:

\parentDirectory
    \subfldr1
        -testfile.txt
    \subfldr2
        -fileOpener.py

I'm trying to script in fileOpener.py to get out of subfldr2, get into subfldr1, and then call an open() on testfile.txt.

From browsing stackoverflow, I've seen people use os and os.path to accomplish this, but I've only found examples regarding files in subdirectories beneath the script's origin.

Working on this, I realized I could just relocate the script into subfldr1 and then all would be well, but my curiosity is piqued as to how this would be accomplished.

EDIT: This question pertains particularly to a Windows machine, as I don't know how drive letters and backslashes would factor into this.


Solution

  • If you know the full path to the file you can just do something similar to this. However if you question directly relates to relative paths, that I am unfamiliar with and would have to research and test.

    path = 'C:\\Users\\Username\\Path\\To\\File'
    
    with open(path, 'w') as f:
        f.write(data)
    

    Edit:

    Here is a way to do it relatively instead of absolute. Not sure if this works on windows, you will have to test it.

    import os
    
    cur_path = os.path.dirname(__file__)
    
    new_path = os.path.relpath('..\\subfldr1\\testfile.txt', cur_path)
    with open(new_path, 'w') as f:
        f.write(data)
    

    Edit 2: One quick note about __file__, this will not work in the interactive interpreter due it being ran interactively and not from an actual file.