簡體   English   中英

如何獲取python可執行文件的文件路徑

[英]How to get path to file for python executable

我正在嘗試通過已經存在的路徑目錄 C:\\ProgramData\\myFolder\\doc.txt 在 python 中獲取路徑以打開和寫入文本文檔,無需創建它,但使其與用戶計算機上的 python 可執行文件一起使用。 例如,如果這樣我在那里得到了文件夾:

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

然后如果我想寫:

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

或打開它:

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

不確定是否正確:

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

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

並使用它例如:

   with open(dataPath) as my_file:  
import os
path = os.environ['HOMEPATH']

我將首先找出放置文件的標准位置。 在 Windows 上,USERPROFILE 環境變量是一個好的開始,而在 Linux/Mac 機器上,您可以依靠 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')

對於 Python 3.x,我們可以

import shutil
shutil.which("python")

實際上, shutil.which可以找到任何可執行文件,而不僅僅是python

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM