北城已荒凉 2011-02-28 01:51 采纳率: 0%
浏览 348
已采纳

找到工作目录文件和文件的目录[重复]

In Python, what commands can I use to find:

  1. the current directory (where I was in the terminal when I ran the Python script), and
  2. where the file I am executing is?
</div>

转载于:https://stackoverflow.com/questions/5137497/find-current-directory-and-files-directory

  • 写回答

15条回答 默认 最新

  • 胖鸭 2011-02-28 01:54
    关注

    To get the full path to the directory a Python file is contained in, write this in that file:

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

    (Note that the incantation above won't work if you've already used os.chdir() to change your current working directory, since the value of the __file__ constant is relative to the current working directory and is not changed by an os.chdir() call.)


    To get the current working directory use

    import os
    cwd = os.getcwd()
    

    Documentation references for the modules, constants and functions used above:

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(14条)

报告相同问题?

悬赏问题

  • ¥15 在grasshopper里DrawViewportWires更改预览后,禁用电池仍然显示
  • ¥15 NAO机器人的录音程序保存问题
  • ¥15 C#读写EXCEL文件,不同编译
  • ¥15 MapReduce结果输出到HBase,一直连接不上MySQL
  • ¥15 扩散模型sd.webui使用时报错“Nonetype”
  • ¥15 stm32流水灯+呼吸灯+外部中断按键
  • ¥15 将二维数组,按照假设的规定,如0/1/0 == "4",把对应列位置写成一个字符并打印输出该字符
  • ¥15 NX MCD仿真与博途通讯不了啥情况
  • ¥15 win11家庭中文版安装docker遇到Hyper-V启用失败解决办法整理
  • ¥15 gradio的web端页面格式不对的问题