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

标签 python

我在下面使用这段代码将一些文本存储在主目录中的文件 ~/.boto 中。

但是我得到这个错误:

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

这是代码:

file = open("~/.boto") 
file.write("test")
file.close()

最佳答案

您需要使用 os.path.expanduser 并使用 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(路径)

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>

默认情况下一个文件只为读打开,如果你想打开写你需要使用w,f你想打开为读写使用r+ 或追加使用 a

如果文件中有内容,则 w覆盖,如果您尝试添加到文件中,则使用 a

关于python - IO错误 : [Errno 2] No such file or directory writing in a file in home directory,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30151355/

相关文章:

python - unicode findall python

python - 是否有一种很好的 pythonic 方法来进行左值排列?

python - 使用 Pandas 将时间序列转换为开始和结束日期

python - 在Python3中设置简单的SAFE http服务器

python - 无法识别 Django 错误

Python 过去 60 个月末

python - 将 n 个 3x3 旋转矩阵的数组与 3 个向量的 3d 数组相乘

python - 无法使用 python 使攻击动画适用于街机库

python - TypeError : B2() takes exactly 1 argument (0 given). ..如果函数完全按照命名或使用变量调用,为什么很重要

python - 排序字典 python 值降序,但键升序