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.
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
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'
Source: Stackoverflow.com