windows – Open File in Another Directory (Python)

windows – Open File in Another Directory (Python)

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.

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())

windows – Open File in Another Directory (Python)

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

Leave a Reply

Your email address will not be published. Required fields are marked *