How to open a file in the same directory as a Python script?

PythonServer Side ProgrammingProgramming

The best and most reliable way to open a file that's in the same directory as the currently running Python script is to use sys.path[0]. It gives the path of the currently executing script. You can use it to join the path to your file using the relative path and then open that file.

Example

For example if you have a file called my_file.txt in the same directory as currently executing script, you can open it using:

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

This will open the file and read its content given that the file resides in the same directory as the script.

Published on 27-Dec-2017 07:56:46