Create log file in the directory of the script in Python

logfilename = os.path.join(
    os.path.dirname(os.path.realpath(__file__)),
    os.path.splitext(os.path.basename(__file__))[0] + '.log')

__file__ is the script file itself. From python3.9 above, it is an absolute path, otherwise the path passed by command line.

os.path.join joins two paths.

realpath returns a absolute path, it also resolves symbolic links. You can also call abspath or normpath.

dirname returns the directory.

splitext returns list of strings split by extension.

Leave a comment

Your email address will not be published. Required fields are marked *