Reputation: 39
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.
Upvotes: 1
Views: 4039
Reputation: 90899
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.
Upvotes: 4