AJN
AJN

Reputation: 1206

python: Cannot access files in directory at the same level

File structure:

packagedir
   |
   |-configdir
       |
       |-cmd1.yaml
       |-cmd2.yaml
   |
   |-main.py

from main.py file I would like to read some yaml files in configdir, the program doesn't find them:

import os.path

cmdfile = os.path.join(os.path.dirname('__file__'), '../configdir', 'cmd1.yaml')

try:
    stream = open(cmdfile)
    rdata = yaml.load(stream)
    if self.rdata:
        for cmd in value[6:len(value)+1]:
            print cmd
    else:
            logging.debug('File ',cmdfile,' is empty')
except IOError:
    print 'File ',cmdfile,' NOT found'

The outcome:

File ../config/INTERNET-cmd.yaml NOT found

Any hint?

Upvotes: 2

Views: 1832

Answers (1)

Vlad274
Vlad274

Reputation: 6844

In that folder structure, your path is wrong. '.' = current directory, '..' = parent directory. When you run this, it is looking for a folder that is a sibling of packagedir (marked with stars).

packagedir
   |
   |-configdir
       |
       |-cmd1.yaml
       |-cmd2.yaml
   |
   |-main.py
******

Your path should be ./configdir because configdir is in the same directory as main.py

NOTE: Technically, this depends on how you're executing main.py, and it is really related to your executing directory. This answers assumes you're running main.py in packagedir

Upvotes: 1

Related Questions