9

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

1 Answer 1

10

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.

Sign up to request clarification or add additional context in comments.

1 Comment

I have realised the problem. It is /root not /home/root. I realised when I looked at the os.path.expanduser() expansion. It was a bit of a facepalm moment - when it did not work I replaced it with /home/root. LOL. Thanks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.