Search code examples
pythonpathexecutablepython-3.5programdata

How to get path to file for python executable


I'm trying to get path in python to open and write in text document by already exist path directory C:\ProgramData\myFolder\doc.txt, no need to create it, but make it work with python executable on user computer. For example if this way I got folder there:

   mypath = os.path.join(os.getenv('programdata'), 'myFolder') 

and then if I want write:

  data = open (r'C:\ProgramData\myFolder\doc.txt', 'w')   

or open it:

    with open(r'C:\ProgramData\myFolder\doc.txt') as my_file:   

Not sure if it is correct:

   programPath = os.path.dirname(os.path.abspath(__file__))

   dataPath = os.path.join(programPath, r'C:\ProgramData\myFolder\doc.txt')

and to use it for example:

   with open(dataPath) as my_file:  

Solution

  • I would start by figuring out a standard place to put the file. On Windows, the USERPROFILE environment variable is a good start, while on Linux/Mac machines, you can rely on HOME.

    from sys import platform
    import os
    if platform.startswith('linux') or platform == 'darwin': 
        # linux or mac
        user_profile = os.environ['HOME']
    elif platform == 'win32': 
        # windows
        user_profile = os.environ['USERPROFILE']
    else:
        user_profile = os.path.abspath(os.path.dirname(__file__))
    filename = os.path.join(user_profile, 'doc.txt')
    with open(filename, 'w') as f:
        # opening with the 'w' (write) option will create
        # the file if it does not already exists
        f.write('whatever you need to change about this file')