user7248941
user7248941

Reputation:

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:  

Upvotes: 0

Views: 1870

Answers (3)

Toon Tran
Toon Tran

Reputation: 378

For Python 3.x, we can

import shutil
shutil.which("python")

In fact, shutil.which can find any executable, rather than just python.

Upvotes: 0

ctaylor08
ctaylor08

Reputation: 16

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')

Upvotes: 0

Thmei Esi
Thmei Esi

Reputation: 442

import os
path = os.environ['HOMEPATH']

Upvotes: 0

Related Questions