Python can't open file "No such file or directory"

18,807

Solution 1

Get the directory of the file, and join it with the file you want to open:

def main():
    dir_path = os.path.dirname(os.path.realpath(__file__))
    lines = os.path.join(dir_path, "lines.txt")
    fh = open(lines)
    for line in fh.readlines():
        print(line)

if __name__ == "__main__": main()

Solution 2

This should do the trick.

def main():
    fh = open('lines.txt')
    for line in fh.readlines():
        print(line)

if __name__ == "__main__":
    import os

    curr_dir = os.path.dirname(os.path.realpath(__file__))  # get's the path of the script
    os.chdir(curr_dir)  # changes the current path to the path of the script
    main()
Share:
18,807
Vincent Tang
Author by

Vincent Tang

I mostly develop with NodeJS / Javascript for full-stack applications, but I dabble in Python . I am a confident developer willing to learn new things as they come. Please check out my GitHub or go to my blog to learn more about projects I have done. Below are a few of my best answers and questions, not based on votes, but rather brevity and helpfulness. As well as projects I've made that solve real-world applications. I contribute to a number of communities besides StackOverflow, listed below QUESTIONS Javascript: Split a string into array matching parameters Javascript access json property javascript how to get json data with api call to redirected url ANSWERS Excel - Seperating / Showing Deleted Duplicated Data Excel VBA Grab Ancestor value from Relational Data Creating URL Paginator with Excel VBA PROJECTS ExcelVBA - Bulk Downloader & Renamer Script used by 300+ database-developers for ETL and local backup COMMUNITIES Alternativeto.net and Software Recommendations Freecodecamp forums solutions SuperUser Forums CONTACT I live on US East Coast. You can reach me here :::::: vincentntang (at) gmail If you email me please write bananas in the subject line.

Updated on June 18, 2022

Comments

  • Vincent Tang
    Vincent Tang almost 2 years
    def main():
        fh = open('lines.txt')
        for line in fh.readlines():
            print(line)
    
    if __name__ == "__main__": main()
    

    Directory files

    enter image description here

    I am on for-working.py file, and am trying to access the lines.txt file within the same working directory. But I get error

    No such file or directory: 'lines.txt'

    Does python need to have an absolute path when opening files?

    why doesn't this relative path work here?

    Running python 3.6

    EDIT ^1 I'm running visualstudio code with the python package extension by Don Jayamanne, and "Code Runner" package to compile/execute python code

    EDIT ^2 Full error:

    Traceback (most recent call last):
      File "c:\www\Ex_Files_Python_3_EssT(1)\Ex_Files_Python_3_EssT\Exercise Files\07 Loops\for-working.py", line 11, in <module>
        if __name__ == "__main__": main()
      File "c:\www\Ex_Files_Python_3_EssT(1)\Ex_Files_Python_3_EssT\Exercise Files\07 Loops\for-working.py", line 7, in main
        fh = open('lines.txt', 'r')
    FileNotFoundError: [Errno 2] No such file or directory: 'lines.txt'
    

    EDIT ^3 checking sys.path

    import sys
    print(sys.path)
    

    produces this information:

    ['c:\\www\\Ex_Files_Python_3_EssT(1)\\Ex_Files_Python_3_EssT\\Exercise Files\\07 Loops', 
    'C:\\Users\\Kagerjay\\AppData\\Local\\Programs\\Python\\Python36\\python36.zip', 'C:\\Users\\Kagerjay\\AppData\\Local\\Programs\\Python\\Python36\\DLLs', 'C:\\Users\\Kagerjay\\AppData\\Local\\Programs\\Python\\Python36\\lib', 'C:\\Users\\Kagerjay\\AppData\\Local\\Programs\\Python\\Python36', 'C:\\Users\\Kagerjay\\AppData\\Local\\Programs\\Python\\Python36\\lib\\site-packages']
    

    EDIT ^4 checking os.getcwd()

    Running

    import os
    print(os.getcwd())
    

    Produces

    c:\www\Ex_Files_Python_3_EssT(1)\Ex_Files_Python_3_EssT\Exercise Files
    

    Well its definitely not in the right subdirectory (needs to cd 07 loops folder, that narrows the issue down

    EDIT ^5 what is in lines.txt file

    My lines.txt file i am opening looks like this. No extra whitespace or anything at start

    01 This is a line of text
    02 This is a line of text
    03 This is a line of text
    04 This is a line of text
    05 This is a line of text
    

    IN SUMMARY

    Visual studio code's Code runner extension needs to be tweaked slightly to open files within a subdirectory so any of the below answers would provide a more robust solution to be independent of any extension / dependencies with the IDE

    import os
    print(os.getcwd())
    

    Is most useful for diagnosing problem to the current directory python interpreter sees