How to get the current file name in python

Asked

Viewed 2,019 times

0

Speak people, speak people, I am making a code creator for sqlite in python.

I was wondering if there is any way to get the name of the current file to pass directly on the function.

currently pass the name by parameters.

1 answer

5


You actually have several options. Of these I present to you three:

import os    
print(os.path.basename(__file__))

import sys
print (sys.argv[0])]

print (__file__)

There is a discussion interesting in the OS regarding the pros and cons of the use of each one. Worth consulting.

Where:

__file__ is the name of the file path from which the module was loaded, if it was loaded from a file. The __file__attribute can be missing for certain types of modules such as C modules that are statically linked to the interpreter; for extension modules dynamically loaded from a shared library, is the path name of shared library file.

  • sys.argv[0](requires import sys) is the name of the script that was called from the command line and can be an absolute path as per detailed in official documentation:

argv[0] is the name of the script (depends on the operating system if this is a path name or not). If the command was executed using the option -c command line for the interpreter, argv[0] will be set to the string '-c'. If no script name has been passed to the python interpreter, argv[0] is the empty string.

The information that made up this reply was removed from here. I thank the user Yoel.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.