0

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:  
  • i think you want `dataPath = os.path.join(programPath, r'myFolder\doc.txt')` ? `__file__` will will you path to your script py file – Skycc Dec 07 '16 at 03:45
  • @Skycc hello, I tried but in this case it does not writes `data = open (dataPath, 'w')` if I use it this way for example –  Dec 07 '16 at 04:03
  • not clear on what you want, i guess its because the dir is not there, `dataPath = os.path.join(os.getenv('programdata'), 'myFolder');os.makedirs(dataPath);with open(os.path.join(dataPath, 'doc.txt'), 'w') as my_file: ` – Skycc Dec 07 '16 at 04:09

3 Answers3

0
import os
path = os.environ['HOMEPATH']
Thmei Esi
  • 434
  • 2
  • 9
0

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')
ctaylor08
  • 16
  • 1
0

For Python 3.x, we can

import shutil
shutil.which("python")

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

Toon Tran
  • 318
  • 3
  • 6