IOError: [Errno 2] No such file or directory writing in a file in home directory

后端 未结 2 404
广开言路
广开言路 2020-12-19 09:57

I have this code below to store some text in a file ~/.boto that is in home directory.

But Im getting this error:

IOError: [Errno 2] No such file or          


        
2条回答
  •  萌比男神i
    2020-12-19 10:40

    Tilde expansions doesn't work inside open(). So python won't be able to expand ~ to /home/user

    A solution would be to read HOME environmental variable using os.environ

    import os
    
    home = os.environ['HOME']
    file = open( home + "/.boto", "w") 
    file.write("test")
    file.close()
    

    OR

    Using os.path.join and os.environ

    >>> import os
    >>> filename = ".boto"
    >>> os.path.join( os.environ['HOME'],  filename)
    /home/user/.boto
    

提交回复
热议问题