1

My code:

boyka = "hello" f = open("~/Desktop/" + boyka + ".txt", "a") f.write(boyka) f.close 

result:

IOError: [Errno 2] No such file or directory: '~/Desktop/hello.txt' 

Shouldn't the script create the file since it's "a" ? How can I fix the code?

I'm using Ubuntu.

2
  • If the problem can't be reproduced, like NightShadeQueen says, the problem must be with the path "~/Desktop/". Commented Aug 31, 2015 at 1:12
  • @NightShadeQueen and m69, Problem solved. Thanks guys Commented Aug 31, 2015 at 1:43

1 Answer 1

4

open() function would not automatically expand the ~ to the users home directory. It is instead trying to create in a directory with exactly that name. I am guessing that is not what you want. In which case you should use - os.path.expanduser() , to expand ~ to the user's home directory. Example -

import os.path f = open(os.path.expanduser(os.path.join("~/Desktop",boyka + ".txt")), "a") 

I would also like to suggest you to use os.path.join() to create the paths , rather than manually creating them.

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

1 Comment

Thanks. Worked exactly like i wanted it to

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.