Search code examples
pythonfilefilenotfounderror

FileNotFoundError: [Error 2] No such file or directory: "DOB.txt, VS Code, Python


I am new to Python and I would appreciate all the help I can get. I'm working in VS Code and I have my Dropbox open in Explorer. I have my text file, DOB.txt in the same folder as my code but when I try to read from it, I get the error message above. There is probably a simple solution that I can't see? Also downloaded files to my desktop and tried to run it from there but with no luck. Also tried to run it with absolute path.

My code so far:

with open("DOB.txt" , "r") as file:     
lines = file.readlines() 
print(lines)

Solution

  • DOB.py appears to be file containing your python code. You are probably mistaking it as the name of the folder containing your text file. I wouldn't want to think that you named your directory DOB.py. To resolve your issue, please verify your actual file path and then use:

    with open("C:\\Users\\mycha\\OneDrive\\Desktop\\FolderContainingYourTextFile\\DOB.txt" , "r") as file:
        lines = file.readlines()
        print(lines)  
    

    NB: If your text file is saved directly on your Desktop, then your file path should be "C:\\Users\\mycha\\OneDrive\\Desktop\\DOB.txt" But again, one wonders if your Desktop is a subdirectory on OneDrive. Please verify your actual filepath.