python - 如何在 Python 中读取主目录

标签 python python-3.x scripting

我正在尝试编写一个 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 是隐藏文件的问题吗?任何方向将不胜感激

最佳答案

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

关于python - 如何在 Python 中读取主目录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58962613/

相关文章:

python - 如何解决导出到 csv 文件时的 unicode 错误 (python)

python - 如何获得负数百分比的计数并按最大负数排序?

python-3.x - 指定与PyErr_SetString一起使用的unicode字符串

windows - Windows 批处理文件中 FOR 循环内的 IF 语句不增加计数器

linux - 在 Bash 脚本中引发错误

python - OperatorNotAllowedInGraphError : using a `tf.Tensor` as a Python `bool` is not allowed: (error in tf Cycle GAN)

python - python中有数学nCr函数吗?

python - openpyxl 如果包含数据则跳过该行

python - 辛普森法则在 Python 中需要永远运行

linux - 合并行并执行日期操作