python-open()不使用路径名

python-open()不使用路径名,python,Python,Python 2.7.1,使用open(),在附加模式和路径名而不是文件名方面遇到问题 它说open()与stdio fopen()一样工作,func在放入append(“a”)时说,如果文件不存在,它应该创建文件 # this works in python, creating file.txt if it doesnt exist >>> fp = open ("file.txt", "a") # this fails to create, but works if th

Python 2.7.1,使用open(),在附加模式和路径名而不是文件名方面遇到问题

它说open()与stdio fopen()一样工作,func在放入append(“a”)时说,如果文件不存在,它应该创建文件

# this works in python, creating file.txt if it doesnt exist
>>> fp = open ("file.txt", "a")

# this fails to create, but works if the file is already extant
>>> fp = open ("~/file.txt", "a")
IOError: [Errno 2] No such file or directory: '~/file.txt'
问题是路径名,而不是文件名。我做错了什么

编辑:Linux签出:

os.path.expanduser(路径) 在Unix和Windows上,返回初始组件为的参数 ~or~用户被该用户的 主目录


很多东西不喜欢路径中的
~
,这会解决它。

我已经意识到这个问题。它是/root而不是/home/root。当我看到os.path.expanduser()扩展时,我意识到了这一点。这是一个有点像facepalm的时刻——当它不起作用时,我用/home/root替换了它。哈哈,谢谢。