Error in opening a file in python
Question: Let's consider the below code:

    
    
    fp=open('PR1.txt','r')
    ch=fp.readlines()
    print "%s" % (' '.join(ch))
    print "\n"
    fp.close()
    

Above code gives an error:

    
    
    IOError: [Errno 2] No such file or directory: 'PR1.txt'
    

But when i am provididng its full location i.e;

    
    
    fp=open('D:/PR1.txt','r')
    

then it is working properly...

IS it necessary to provide full location of file or there is some other way
too?


Answer: No, it is not necessary, but you need to be certain you are running your
script with the right working directory. Your script working directory is
evidently _not_ `D:/`.

In practice, it is better to only use relative paths if you are in full
control of the working directory. You can get the current working directory
with [`os.getcwd()`](http://docs.python.org/2/library/os.html#os.getcwd) and
set it with [`os.chdir()`](http://docs.python.org/2/library/os.html#os.chdir)
but using absolute paths is usually better.

For paths relative to the _current module or script_ , use the `__file__`
global to produce a directory name:

    
    
    import os.path
    
    here = os.path.dirname(os.path.absolute(__file__))
    

then use `os.path.join()` to make relative paths absolute in reference to
`here`.

