Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
620 views
in Technique[技术] by (71.8m points)

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

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 directory: '~/.boto'

This is the code:

file = open("~/.boto") 
file.write("test")
file.close()
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 the argument with an initial component of ~ or ~user replaced by that user‘s home directory.

On Unix, an initial ~ is replaced by the environment variable HOME if it is set; otherwise the current user’s home directory is looked up in the password directory through the built-in module pwd. An initial ~user is looked up directly in the password directory.

On Windows, HOME and USERPROFILE will be used if set, otherwise a combination of HOMEPATH and HOMEDRIVE will be used. An initial ~user is handled by stripping the last directory component from the created user path derived above.

If the expansion fails or if the path does not begin with a tilde, the path is returned unchanged.

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>

By default a file is only open for reading, if you want to open for writing you need to use w, f you want to open for reading and writing use r+ or to append use a.

If you have content in the file then w is going to overwrite, if you are trying to add to the file then use a


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...