IOError: [Errno 2] There is no such file or directory writing to a file in the home directory

I have the following code to store some text in the ~ / .boto file, which is in the home directory.

But I get this error:

IOError: [Errno 2] No such file or directory: '~/.boto'

This is the code:

file = open("~/.boto") 
file.write("test")
file.close()
+4
source share
2 answers

You need to use os.path.expanduser and open for writing with w:

import  os

# with will automatically close your file
with open(os.path.expanduser("~/.boto"),"w") as f:
    f.write("test") # write to file

os.path.expanduser (path)

On Unix and Windows, return an argument with the original component ~ or ~ of the user replaced by that user's home directory.

Unix ~ HOME, ; pwd. ~ .

Windows, HOME USERPROFILE , , HOMEPATH HOMEDRIVE. ~ , .

, .

In [17]: open("~/foo.py")
---------------------------------------------------------------------------
IOError                                   Traceback (most recent call last)
<ipython-input-17-e9eb7789ac68> in <module>()
----> 1 open("~/foo.py")

IOError: [Errno 2] No such file or directory: '~/foo.py'

In [18]: open(os.path.expanduser("~/foo.py"))
Out[18]: <open file '/home/padraic/foo.py', mode 'r' at 0x7f452d16e4b0>

, , w, f, , r+ a.

, w , , a

+15

open(). , python ~ /home/user

, HOME, os.environ

import os

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

os.path.join os.environ

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

All Articles