简体   繁体   中英

How to read home directory in Python

I'm trying to write a python script that will copy some files into certain directories and then add a source to my .bash_profile . I am having some issues even getting this script off the ground. I am currently trying to just check if there is a .bash_profile and if so read the contents

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 I take my code out of the if statement I receive this error

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'

I can't seem to find any information on how to read into the home ~ directory or is this an issue with .bash_profile being a hidden file? Any direction would be much appreciated

You need to call os.path.expanduser(file_path) to expand the path that starts with ~ .

  • ~ to get home path from this use os.path.expanduser function.
import os
f = open(os.path.expanduser('~/.bash_profile') , "r")

~ is expanded by the shell, it has no special meaning for python.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM