Home > Software engineering >  Code not able to locate file from within the same path as the program itself
Code not able to locate file from within the same path as the program itself

Time:11-08

My program is located under C:\Users\Username\pycode.py

My file to be called within the program is located under C:\Users\Username\<filename>

The file and the code are in the same directory.

When I call from within the program using the below set of codes,

import os; import sys
with open(os.path.join(sys.path[0], "file1.txt"), "r") as fn1:
    print(fn1.read())

the Py code picks up the file and executes the applied methods on it. However, when I don't use the above code and use as:

fn1 = open("file1.txt", "r")
print(fn1.read())

There is only an error that the file does not exist.

Any thoughts and ideas, what is missing to make the file within the local directory as the py code to recognize the file.

If it's relevant, I'm a beginner using VSCode on Windows 10.

CodePudding user response:

Speaking from personal experience, it happens to me when I am using vscode and I am in a directory say d:/Desktop/python programs. But the file I want to open() is in the directory d:/Desktop/python programs/fun.

In this case it is not sufficient for me to use the path like "filename". Instead I need to use "/fun/filename". This is even though the file I am working on is in the fun folder.

So perhaps you could go to the terminal in VSCode (your IDE) and run cd "path to your file" and that should solve the problem

Try running the following code and see what output you get

import os
print(os.getcwd())

In my case this would print d:/Desktop/python programs

  • Related