Search code examples
pythonshellfilepathzsh

Add to ~/.zshrc file with python


I'm trying to write a cli that will take a users path that they input into the command line, then add this path to the correct path file depending on their shell - in this case zsh. I have tried using:

    shell = str(subprocess.check_output("echo $SHELL", shell=True))
    click.echo("Enter the path you would like to add:")
    path = input()
    if 'zsh' in shell:
        with open(".zshrc", 'w') as zsh:
            zsh.write(f'export PATH="$PATH:{path}"')

This throws no errors but doesn't seem to add to the actual ~./zshrc file. Is there a better way to append to the file without manually opening the file and typing it in?

New to this so sorry if it's a stupid question...


Solution

  • Open the file in append mode. Your code also assumes that the current working directory is the user's home directory, which is not a good assumption to make.

    from pathlib import Path
    import os
    
    
    if 'zsh' in os.environ.get("SHELL", ""):
        with open(Path.home() / ".zshrc", 'a') as f:
            f.write(f'export PATH={path}:$PATH')

    with (Path.home() / ".zshrc').open("a") as f: would work as well.

    Note that .zprofile would be the preferred location for updating an envirornent variable like PATH, rather than .zshrc.