Search code examples
pythonioerror

Python IOError: [Errno 2] No such file or directory, how to enter model directory


My file system is:

main.py
method
  |- __init__.py
  |- a.txt
  |- method.py

method.py is:

def method():
with open('a.txt') as f:
    print f.readlines()

main.py is:

if __name__ == '__main__':
    from method.method import method as meth
    meth()

When I run the main.py, IOError: [Errno 2] No such file or directory: 'a.txt'.

I find the run directory is not in ./method/, so it find not the 'a.txt', how to solve it?

Thank u! :D


Solution

  • Try like this,

    import os
    full_path = os.path.realpath(__file__)
    file_path = '%s/a.txt' % os.path.dirname(full_path) 
    def method():
      with open(file_path) as f:
        print f.readlines()