查找当前目录和文件目录

2024-04-27 03:02:11 发布

您现在位置:Python中文网/ 问答频道 /正文

在Python中,我可以使用哪些命令来查找:

  1. 当前目录(运行Python脚本时我在终端中的位置),以及
  2. 我正在执行的文件在哪里?

Tags: 文件命令脚本终端
3条回答

当前工作目录:^{}

^{} attribute可以帮助您找到正在执行的文件的位置。这篇文章解释了一切:How do I get the path of the current executed file in Python?

您可能会发现这是一个有用的参考:

import os

print("Path at terminal when executing this file")
print(os.getcwd() + "\n")

print("This file path, relative to os.getcwd()")
print(__file__ + "\n")

print("This file full path (following symlinks)")
full_path = os.path.realpath(__file__)
print(full_path + "\n")

print("This file directory and name")
path, filename = os.path.split(full_path)
print(path + ' --> ' + filename + "\n")

print("This file directory only")
print(os.path.dirname(full_path))

要获取包含Python文件的目录的完整路径,请在该文件中写入以下内容:

import os 
dir_path = os.path.dirname(os.path.realpath(__file__))

(请注意,如果您已经使用os.chdir()更改了当前工作目录,则上面的咒语将不起作用,因为__file__常量的值是相对于当前工作目录的,并且不会被os.chdir()调用更改。)


获取当前工作目录的使用

import os
cwd = os.getcwd()

上面使用的模块、常数和函数的文档参考:

  • ^{}^{}模块。
  • ^{}常数
  • ^{}(返回指定文件名的规范路径,消除路径“中遇到的任何符号链接)
  • ^{}(返回路径名path“的目录名)
  • ^{}(返回表示当前工作目录的字符串“”)
  • ^{}“将当前工作目录更改为path

相关问题 更多 >