python - open() 不适用于路径名

9 投票
1 回答
1917 浏览
提问于 2025-04-16 18:04

我在用Python 2.7.1的时候,使用open()函数,遇到了关于追加模式和路径名的问题,而不是文件名。

它说open()的工作方式和C语言里的fopen()函数差不多,当我把模式设为追加("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系统。

1 个回答

11

看看 os.path.expanduser() 这个函数:

os.path.expanduser(路径)

在Unix和Windows系统上,这个函数会把路径中开头的 ~ 或者 ~用户 替换成那个用户的主目录。

很多程序在处理路径时不喜欢 ~ 这个符号,这个函数可以帮你解决这个问题。

撰写回答