网络编程
位置:首页>> 网络编程>> Python编程>> 使用Python获取当前工作目录和执行命令的位置

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

作者:潘高  发布时间:2022-08-12 09:06:16 

标签: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

来源:https://blog.csdn.net/u011236348/article/details/89203924

0
投稿

猜你喜欢

手机版 网络编程 asp之家 www.aspxhome.com