Open file in a relative location in Python

python open file absolute path
how to give file path in python
python relative path current directory
python write file to current directory
python file path windows
python save file to new directory
python get relative path
python open file in parent directory

Suppose python code is executed in not known by prior windows directory say 'main' , and wherever code is installed when it runs it needs to access to directory 'main/2091/data.txt' .

how should I use open(location) function? what should be location ?

Edit :

I found that below simple code will work..does it have any disadvantages ?


With this type of thing you need to be careful what your actual working directory is. For example, you may not run the script from the directory the file is in. In this case, you can't just use a relative path by itself.

If you are sure the file you want is in a subdirectory beneath where the script is actually located, you can use __file__ to help you out here. __file__ is the full path to where the script you are running is located.

So you can fiddle with something like this:

import os
script_dir = os.path.dirname(__file__) #<-- absolute dir the script is in
rel_path = "2091/data.txt"
abs_file_path = os.path.join(script_dir, rel_path)

Reading file using relative path in python project, data/test.csv") with open(path) as f: test = list(csv.reader(f)). Note, from python 3.4, __file__ is always absolute for imported modules and you  Open file in a relative location in Python python file path relative-path Suppose python code is executed in not known by prior windows directory say 'main' , and wherever code is installed when it runs it needs to access to directory 'main/2091/data.txt' .

This code works fine:

import os

def readFile(filename):
    filehandle = open(filename)

fileDir = os.path.dirname(os.path.realpath('__file__'))
print fileDir

#For accessing the file in the same folder
filename = "same.txt"

#For accessing the file in a folder contained in the current folder
filename = os.path.join(fileDir, 'Folder1.1/same.txt')

#For accessing the file in the parent folder of the current folder
filename = os.path.join(fileDir, '../same.txt')

#For accessing the file inside a sibling folder.
filename = os.path.join(fileDir, '../Folder2/same.txt')
filename = os.path.abspath(os.path.realpath(filename))
print filename

Chapter 8 – Reading and Writing Files, Figure 8-2. The relative paths for folders and files in the working directory C:\​bacon Read mode is the default mode for files you open in Python. But if you don't  Relative Paths in Python. So this is how you can get the relative paths in Python. Not really an elegant way but this is the way to do it. Please let me know if this tutorial helped. Also, don’t forget to add your comments/questions in the comments section. Thank you!

I created an account just so I could clarify a discrepancy I think I found in Russ's original response.

For reference, his original answer was:

import os
script_dir = os.path.dirname(__file__)
rel_path = "2091/data.txt"
abs_file_path = os.path.join(script_dir, rel_path)

This is a great answer because it is trying to dynamically creates an absolute system path to the desired file.

Cory Mawhorter noticed that __file__ is a relative path (it is as well on my system) and suggested using os.path.abspath(__file__). os.path.abspath, however, returns the absolute path of your current script (i.e. /path/to/dir/

To use this method (and how I eventually got it working) you have to remove the script name from the end of the path:

import os
script_path = os.path.abspath(__file__) # i.e. /path/to/dir/
script_dir = os.path.split(script_path)[0] #i.e. /path/to/dir/
rel_path = "2091/data.txt"
abs_file_path = os.path.join(script_dir, rel_path)

The resulting abs_file_path (in this example) becomes: /path/to/dir/2091/data.txt

How do I interact with files in Python?, A relative file path is interpreted from the perspective your current working python: can't open file '': [Errno 2] No such file or  If I understand your question correctly then you should study this code: [code]#!/usr/bin/env python from __future__ import print_function import os, sys if __name__

It depends on what operating system you're using. If you want a solution that is compatible with both Windows and *nix something like:

from os import path

file_path = path.relpath("2091/data.txt")
with open(file_path) as f:
    <do stuff>

should work fine.

The path module is able to format a path for whatever operating system it's running on. Also, python handles relative paths just fine, so long as you have correct permissions.


As mentioned by kindall in the comments, python can convert between unix-style and windows-style paths anyway, so even simpler code will work:

with open("2091/data/txt") as f:
    <do stuff>

That being said, the path module still has some useful functions.

File Path and CWD, On this page: open(), file path, CWD ('current working directory'), r 'raw string' prefix, os.getcwd(), Python assumes that it starts in the CWD (a "relative path"). open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None) file is a path-like object giving the pathname (absolute or relative to the current working directory) of the file to be opened or an integer file descriptor of the file to be wrapped.

I spend a lot time to discover why my code could not find my file running Python 3 on the Windows system. So I added . before / and everything worked fine:

import os

script_dir = os.path.dirname(__file__)
file_path = os.path.join(script_dir, './output03.txt')
fptr = open(file_path, 'w')

Working with Files & the Filesystem in Python: Reference and , Examples on how to perform filesystem-related tasks using python. Relative to absolute path; Relative to absolute path in Jupyter; File name from path; Path from with open("path/to/file") as f: for line in f: # process the line. On this page: open(), file path, CWD ('current working directory'), r 'raw string' prefix, os.getcwd(), os.chdir(). Referencing a File with a Full Path and Name As seen in Tutorials #15 and #16 , you can refer to a local file in Python using the file's full path and file name.

11.1. os.path — Common pathname manipulations, Return True if path refers to an existing path or an open file descriptor. "foo") represents a path relative to the current directory on drive C: (c:foo), not c:\foo. 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.

pathlib — Object-oriented filesystem paths, Listing Python source files in this directory tree: >>> Opening a file: >>> >>> with Compute a version of this path relative to the path represented by other. The Wrong Solution: Building File Paths by Hand. Let’s say you have a data folder that contains a file that you want to open in your Python program: This is the wrong way to code it in Python: Notice that I’ve hardcoded the path using Unix-style forward slashes since I’m on a Mac. This will make Windows users angry.

Pathnames explained: Absolute, relative, UNC, and URL, The easiest way is to convert pathnames into Python rawstrings using the "r directive", A relative path refers to a location that is relative to a current directory. To set this option, look under the File menu, click Document Properties, then click the This will open the Data Source Options dialog box, and you can specify  Read whole file into string. Read file line by line into string. This is easy with python: You can also use f.readline() to read a whole line (dangerous if the file has no line breaks) or, which takes an argument indicating the maximum number of bytes to be read into memory.

  • You're using unescaped backslashes. That's one disadvantage.
  • Several disadvantages. 1) As per @orip, use forward slashes for paths, even on windows. Your string won't work. Or use raw strings like r"\2091\sample.txt". Or escape them like "\\2091\\sample.txt" (but that is annoying). Also, 2) you are using getcwd() which is the path you were in when you execute the script. I thought you wanted relative to the script location (but now am wondering). And 3), always use os.path functions for manipulating paths. Your path joining line should be os.path.join(os.getcwd(), file) 4) the ; is pointless
  • And for good measure... 5) use context guards to keep it clean and avoid forgetting to close your file: with open(path, 'r+') as fp:. See here for the best explanation of with statements I've seen.
  • Similar question:…
  • I found that below simple code will work..does it have any disadvantages ? <pre> file="\sample.txt" path=os.getcwd()+str(loc)+file fp=open(path,'r+');<code>
  • @Arash The disadvantage to that is the cwd (current working directory) can be anything, and won't necessarily be where your script is located.
  • __file__ is a relative path (at least on my setup, for some reason), and you need to call os.path.abspath(__file__) first. osx/homebrew 2.7
  • os.path.dirname(file) is not working for me in Python 2.7. It is showing NameError: name '__file__' is not defined
  • @Soumendra I think you are trying it in the console. Try it in a *.py file.
  • For me accessing the file in the parent folder of the current folder did not worked..the .. is added as string..
  • Did not work on Windows. Path to file is correct but Python states "file not found" and shows the path with \\ separators.
  • You could even combine both approaches for the simpler os.path.dirname(os.path.abspath(__file__))
  • @LukeTaylor Indeed that would be better than trying to replicate the os.path.dirname functionality yourself as I did in my answer last year.