当前位置:主页 > 软件编程 > Python代码 >

使用Python获取当前工作目录和执行命令的位置

时间:2021-10-12 09:42:37 | 栏目:Python代码 | 点击:

获取当前工作目录

import sys

print(sys.path[0])

获取执行命令的位置

import os

print(os.getcwd())

补充知识:Python获取当前执行文件,根据某一级目录名称,获取此目录名称所在的绝对路径

假如当前文件绝对路径:E:\learn\python\我的file\my.py

#coding:utf-8
import os
 
#dirName:上级目录名称
#sysCoding:系统编码格式
#targetCoding:转换目标编码格式
def get_dir_realpath(dirName,sysCoding,targetCoding):
  path = os.path.split(os.path.realpath(__file__))[0].decode(sysCoding).encode(targetCoding)
  dirList = path.split("\\")
  length = len(dirList)
  for _ in range(1,length):
    fileName = os.path.split(path)[1]
    path = os.path.split(path)[0]
    if fileName == dirName:
      return path
      break
  return ""
    
print get_dir_realpath("我的file",'cp936',"utf-8") 执行结果:E:\learn\python

print get_dir_realpath("python",'cp936',"utf-8") 执行结果:E:\learn

您可能感兴趣的文章:

相关文章