Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 251
dbishop Avatar asked Sep 09 '15 03:09

dbishop


People also ask

How do I point a directory in Python?

To change the current working directory in Python, use the chdir() method. The method accepts one argument, the path to the directory to which you want to change. The path argument can be absolute or relative.


2 Answers

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.

like image 179
Jared Mackey Avatar answered Oct 06 '22 11:10

Jared Mackey


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()) 
like image 21
SaretMagnoslove Avatar answered Oct 06 '22 11:10

SaretMagnoslove