Open file in another directory (Python)

I was always confused about directory traversal in Python and had a situation in which I was curious: I have a file that I want to get in a directory essentially parallel to the one I am currently in. Given this directory structure:

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

I am trying to script in fileOpener.py to exit subfldr2, get into subfldr1, and then call open () on testfile.txt.

From viewing stackoverflow, I saw that people use os and os.path to accomplish this, but I found sample files in subdirectories under the script source.

While working on this, I realized that I can just move the script to subfldr1, and then everything will be fine, but my curiosity is caused by how this is achieved.

EDIT: This question applies in particular to a Windows machine, since I don't know how disk factors and backslashes will affect this.

+5
source share
2 answers

If you know the full path to the file, you can just do something like this. However, if you ask the question directly, relate to the relative paths that I am not familiar with and will need 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 this relatively instead of the absolute. Not sure if this works in 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 short note about __file__ , this will not work in the interactive interpreter due to the fact that it runs interactively, and not from the actual file.

+9
source
 import os import os.path import shutil 

You will 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 list / list of all 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 for a tuple for the desired directory and open the file in this directory:

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

Then you can do stuf with the complete file file 'file'

+2
source

All Articles