Michael
Michael

Reputation: 42050

Reading file from the same directory as the python module

Suppose I have got python module foo.py and file myfile.txt that reside in the same directory. foo.py contains the following code to read myfile.txt:

from os import path
myfile_path = path.join(path.dirname(__file__), 'myfile.txt')
myfile = open(myfile_path)

I found myself writing path.join(path.dirname(__file__), '...') over and over again in different modules. Is there a shorter and simpler way to read a file from the same directory as the python module ?

Upvotes: 2

Views: 5249

Answers (2)

user10523691
user10523691

Reputation: 41

You can use data = open('myfile.txt', 'r').read(), without using path.

Upvotes: 1

Max
Max

Reputation: 186

I don't know if this applies to your exact situation, but here is what I have found:

There should be a JSON file that defines how the debugger should work. For me, I use VS Code, and I use the Microsoft Python debugger. It uses a file called launch.json, and contains an array called "configurations":

"configurations": [
    {
        "name": "Python: Current File",
        "type": "python",
        "request": "launch",
        "program": "${file}",
        "console": "internalConsole"
]

It is missing a key called "cwd", short for "current working directory" (you can read more about it here). If you add it with the value of blank quotes "", then when Python searches for a file without a specified path, it will search within the same folder. Showing the last few lines of what that looks like:

        "program": "${file}",
        "console": "internalConsole",
        "cwd": ""
]

For more general advice, your debugger, or whatever else is running your Python file, needs to have its working directory correctly defined.

I realize the post is nineteen months old at some point, but I hope this helps someone!

Upvotes: 1

Related Questions