Python version: 2.6.6
I'm trying to use Python to create a file that doesn't exist by using open('file/path/file_name', 'w')
. However, I can't hard code the file path in like that since I need to pass it in as a variable containing a path specified by the user.
This works: open('/home/root/my_file.txt', 'w')
But my code doesn't:
import os
import sys
input = sys.argv[1] # assume it's "/home/root"
path = os.path.join(input, "my_file.txt")
f = open(path, 'w')
Which causes an exception IOError: [Errno 2] No such file or directory: '/home/root/my_file.txt'
I've also tried some other modes other than "w", like "w+" and "a", but none of them worked.
Could anyone tell me how I can fix this problem? Is it caused by the my incorrect way of using it or is it because of the version of Python I'm using?
Thanks.
UPDATE:
I have found the solution to my problem: my carelessness of forgetting to create the directory which doesn't exist yet. Here's my final code:
import os, errno
import sys
input = sys.argv[1]
try:
os.makedirs(input)
except OSError as e:
if e.errno == errno.EEXIST and os.path.isdir(input):
pass
else:
raise
path = os.path.join(input, "my_file.txt")
with open(path, "w") as f:
f.write("content")
Code adapted from this SO answer