[python] 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.

This question is related to python windows os.path

The answer is


from pathlib import Path

data_folder = Path("source_data/text_files/")
file_to_open = data_folder / "raw_data.txt"

f = open(file_to_open)
print(f.read())

Its a very old question but I think it will help newbies line me who are learning python. If you have Python 3.4 or above, the pathlib library comes with the default distribution.

To use it, you just pass a path or filename into a new Path() object using forward slashes and it handles the rest. To indicate that the path is a raw string, put r in front of the string with your actual path.

For example,

from pathlib import Path

dataFolder = Path(r'D:\Desktop dump\example.txt')

Source: The easy way to deal with file paths on Windows, Mac and Linux

(unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: truncated \UXXXXXXXX escape


import os
import os.path
import shutil

You find your current directory:

d = os.getcwd() #Gets the current working directory

Then you change one directory up:

os.chdir("..") #Go up one directory from working directory

Then you can get a tupple/list of all the directories, for one directory up:

o = [os.path.join(d,o) for o in os.listdir(d) if os.path.isdir(os.path.join(d,o))] # Gets all directories in the folder as a tuple

Then you can search the tuple for the directory you want and open the file in that directory:

for item in o:
    if os.path.exists(item + '\\testfile.txt'):
    file = item + '\\testfile.txt'

Then you can do stuf with the full file path 'file'


Examples related to python

programming a servo thru a barometer Is there a way to view two blocks of code from the same file simultaneously in Sublime Text? python variable NameError Why my regexp for hyphenated words doesn't work? Comparing a variable with a string python not working when redirecting from bash script is it possible to add colors to python output? Get Public URL for File - Google Cloud Storage - App Engine (Python) Real time face detection OpenCV, Python xlrd.biffh.XLRDError: Excel xlsx file; not supported Could not load dynamic library 'cudart64_101.dll' on tensorflow CPU-only installation

Examples related to windows

"Permission Denied" trying to run Python on Windows 10 A fatal error occurred while creating a TLS client credential. The internal error state is 10013 How to install OpenJDK 11 on Windows? I can't install pyaudio on Windows? How to solve "error: Microsoft Visual C++ 14.0 is required."? git clone: Authentication failed for <URL> How to avoid the "Windows Defender SmartScreen prevented an unrecognized app from starting warning" XCOPY: Overwrite all without prompt in BATCH Laravel 5 show ErrorException file_put_contents failed to open stream: No such file or directory how to open Jupyter notebook in chrome on windows Tensorflow import error: No module named 'tensorflow'

Examples related to os.path

Open File in Another Directory (Python) pros and cons between os.path.exists vs os.path.isdir Python os.path.join() on a list