Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to open a file in the parent directory in python in AppEngine?

How to open a file in the parent directory in python in AppEngine?

I have a python file module/mod.py with the following code

f = open('../data.yml')
z = yaml.load(f)
f.close()

data.yml is in the parent dir of module. The error I get is

IOError: [Errno 13] file not accessible: '../data.yml'

I am using AppEngine SDK 1.3.3.

Is there a work around for this?

like image 808
GeekTantra Avatar asked May 02 '10 11:05

GeekTantra


3 Answers

The open function operates relative to the current process working directory, not the module it is called from. If the path must be module-relative, do this:

import os.path
f = open(os.path.dirname(__file__) + '/../data.yml')
like image 173
Marcelo Cantos Avatar answered Oct 12 '22 13:10

Marcelo Cantos


Having encountered this question and not being satisfied with the answer, I ran across a different solution. It took the following to get what I wanted.

  1. Determine the current directory using os.path.dirname:

    current_directory = os.path.dirname(__file__)

  2. Determine the parent directory using os.path.split:

    parent_directory = os.path.split(current_directory)[0] # Repeat as needed

  3. Join parent_directory with any sub-directories:

    file_path = os.path.join(parent_directory, 'path', 'to', 'file')

  4. Open the file:

    open(file_path)

Combined together:

open(os.path.join(os.path.split(os.path.dirname(__file__))[0], 'path', 'to', 'file')
like image 10
ThatsAMorais Avatar answered Oct 12 '22 12:10

ThatsAMorais


🔰🔰 alternative solution 🔰🔰

You can also use the sys module to get the current working directory.
Thus, another alternative to do the same thing would be:

import sys
f = open(sys.path[0] + '/../data.yml')
like image 3
anjandash Avatar answered Oct 12 '22 14:10

anjandash