简体   繁体   中英

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:  
import os
path = os.environ['HOMEPATH']

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

For Python 3.x, we can

import shutil
shutil.which("python")

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM