40

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.

dbishop
  • 910
  • 2
  • 8
  • 13
  • Do you need to set the current directory to `subfldr1` *and* open the file inside? Or do you only need to open the file, but whether your current directory has changed does not matter? – Dan Lowe Sep 09 '15 at 03:48
  • @DanLowe I don't need to actually change the current directory, just access testfile.txt from where I'm at in subfldr2 – dbishop Sep 09 '15 at 03:55
  • Does this answer your question? [How to read a file in other directory in python](https://stackoverflow.com/questions/13223737/how-to-read-a-file-in-other-directory-in-python) – Melebius May 25 '20 at 11:46
  • 1
    I'm surprised that most answers don't make use of `..`. When you use `..` in a path, that means the parent directory. So in this case, if you are currently in `subfldr2`, then `..` is `parentDirectory`, and `../subfldr1/testfile.txt` is the _relative path_ (relative to your current working directory) to the file. – AndrewF Feb 16 '22 at 01:31

6 Answers6

48

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.

Jared Mackey
  • 3,998
  • 4
  • 31
  • 50
  • 1
    I figured it would be something along this line, but I'm asking specifically for a Windows machine, as the addition of the drive letter and backslashes I'm sure complicates this a bit. Editing the question now to specify that. – dbishop Sep 09 '15 at 03:47
  • Slightly pedantic note- you may want to make it `r'PATH'` or escape the `\\`s – theB Sep 09 '15 at 03:53
  • Was wondering why it didn't work on the first go, but apparently had to change __file__ to __name__. Works well though, and much simpler and pythonic than I had anticpated. Thanks! @electrometro – dbishop Sep 09 '15 at 04:04
  • Welcome. There are tons of other ways to do this. This was just the first to come to mind. – Jared Mackey Sep 09 '15 at 04:05
  • @electrometro This is true, however this seems to be a pretty simple way to go about it, which I much prefer – dbishop Sep 09 '15 at 04:14
  • 3
    You could just simply do `os.path.join(cur_path, '..\\subfldr1\\testfile.txt')` for an absolute path without having to create a relative path from the current working directory, or more portably `os.path.join(cur_path, '..', 'subfldr', 'testfile.txt')` – AChampion Sep 09 '15 at 04:26
17
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())
SaretMagnoslove
  • 301
  • 2
  • 4
11

This is applicable at the time of answer, Sept. 2015

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'

Roan
  • 892
  • 15
  • 27
7

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

raman
  • 93
  • 2
  • 8
2

I think the simplest way to search a file in another folder is:

from pathlib import Path

root_folder = Path(__file__).parents[1]

my_path = root_folder / "doc/foo.json"

with open(my_path, "r") as f:
  data = json.load(f)

With parents[i] you can go back as many directories as you want without writing "../../../"

Here, I have the following architecture:

-> root
  -> routes
    myscript
  -> doc
    foo.json
Timothee W
  • 149
  • 7
0
import os

main_path = os.path.dirname(__file__)
file_path = os.path.join(main_path, 'subfldr1\\testfile.txt')
f = open(file_path)
  • 1
    Your answer could be improved by adding more information on what the code does and how it helps the OP. – Tyler2P Jul 09 '22 at 18:24