【问题标题】:Is there a way to view the directory that a file is in using python? [duplicate]有没有办法使用python查看文件所在的目录? [复制]
【发布时间】:2019-09-06 05:36:43
【问题描述】:

对于我正在使用 python 进行的项目,我需要能够查看文件所在的目录。本质上它是一个查找功能,但是我不知道如何使用 python 来做到这一点。

我尝试在 google 上搜索,但只找到了如何查看目录中的文件。我想使用文件名查看目录。

总结一下:我不知道目录,想用里面的文件找到它。

谢谢。

【问题讨论】:

    标签: python directory


    【解决方案1】:

    在 Python 中,用于处理本地文件的常用标准库有:

    • os.path
    • 操作系统
    • 路径库

    如果你有一个文件的路径并且想要它的目录,那么我们需要解压它:

    >>> import os
    >>> filepath = '/Users/guest/Desktop/blogpost.md'
    >>> os.path.dirname(filepath) # Returns a string of the directory name
    '/Users/guest/Desktop'
    

    如果你想要你的脚本的目录,你需要搜索的关键字是“当前工作目录”:

    >>> import os
    >>> os.getcwd() # returns a string of the current working directory
    '/Users/guest/Desktop'
    

    还可以查看this SO post,了解您可能需要的更多常见操作。

    【讨论】:

      【解决方案2】:

      这就是我所做的:

      import os
      print(os.getcwd())
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-06-25
        • 2021-01-22
        • 1970-01-01
        • 2011-12-23
        • 1970-01-01
        • 2020-04-16
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多