【问题标题】:How to get path to file for python executable如何获取python可执行文件的路径
【发布时间】:2016-12-07 03:31:58
【问题描述】:

我正在尝试通过已经存在的路径目录 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:  

【问题讨论】:

  • 我想你想要dataPath = os.path.join(programPath, r'myFolder\doc.txt')__file__ 将为您提供脚本 py 文件的路径
  • @Skycc 你好,我试过了,但在这种情况下,如果我以这种方式使用它,它不会写入data = open (dataPath, 'w')
  • 不清楚你想要什么,我猜是因为目录不存在,dataPath = os.path.join(os.getenv('programdata'), 'myFolder');os.makedirs(dataPath);with open(os.path.join(dataPath, 'doc.txt'), 'w') as my_file:

标签: python path executable python-3.5 programdata


【解决方案1】:

我会先找出一个标准的文件放置位置。在 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')

【讨论】:

    【解决方案2】:
    import os
    path = os.environ['HOMEPATH']
    

    【讨论】:

      【解决方案3】:

      对于 Python 3.x,我们可以

      import shutil
      shutil.which("python")
      

      事实上,shutil.which 可以找到any 可执行文件,而不仅仅是python

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-09-21
        • 1970-01-01
        • 1970-01-01
        • 2021-08-24
        • 1970-01-01
        • 1970-01-01
        • 2011-02-07
        相关资源
        最近更新 更多