Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python - open() not working with path names

Tags:

python

Python 2.7.1, using open(), and having trouble with append mode and pathname instead of filename.

It says open() works as stdio fopen(), and that func when put into append ("a") says it's supposed to create the file if it doesn't exist.

# 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'

The problem is being a pathname, not a filename. What am I doing anything wrong?

edit: Linux

like image 351
Aroyo Avatar asked May 21 '11 00:05

Aroyo


1 Answers

Check out os.path.expanduser():

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.

A lot of things don't like ~ in paths and this will fix it.

like image 109
Brendan Long Avatar answered Sep 21 '22 08:09

Brendan Long