【问题标题】:How to read home directory in Python如何在 Python 中读取主目录
【发布时间】:2020-03-16 15:48:54
【问题描述】:

我正在尝试编写一个 python 脚本,它将一些文件复制到某些目录中,然后将源添加到我的.bash_profile。我什至遇到了一些问题,甚至让这个脚本脱离了地面。我目前正在尝试检查是否有.bash_profile,如果有,请阅读内容

import os.path

def main():
    file_path = '~/.bash_profile'
    file_exists = os.path.isfile(file_path)

    if file_exists:
        print('file exists')
        f = open(file_path, "r")
        if f.mode == "r":
            contents = f.read()
            print(contents)
    else:
        print('file does not exist')

if __name__== "__main__":
    main()

如果我将代码从 if 语句中取出,我会收到此错误

Traceback (most recent call last):
  File "bash_install.py", line 9, in <module>
    main()
  File "bash_install.py", line 3, in main
    f = open('~/.bash_profile', "r")
IOError: [Errno 2] No such file or directory: '~/.bash_profile'

我似乎找不到任何有关如何读取主目录 ~ 的信息,或者这是 .bash_profile 是隐藏文件的问题?任何方向将不胜感激

【问题讨论】:

  • 您使用的是什么操作系统? ~ 是 home 而不是 root(在基于 linux 的机器上)。根是/
  • 您正在寻找 home,而不是 root

标签: python python-3.x scripting


【解决方案1】:

你需要调用os.path.expanduser(file_path)来扩展以~开头的路径。

【讨论】:

  • TIL。谢谢你。
  • 像魅力一样工作。 =)
【解决方案2】:
  • ~ 从此使用 os.path.expanduser 函数获取主路径。
import os
f = open(os.path.expanduser('~/.bash_profile') , "r")

【讨论】:

    【解决方案3】:

    ~由shell扩展,对python没有特殊意义。

    【讨论】:

      猜你喜欢
      • 2020-10-06
      • 1970-01-01
      • 2011-08-16
      • 2020-03-11
      • 1970-01-01
      • 2015-11-30
      • 2021-09-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多