Reputation: 1017
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
Upvotes: 2
Views: 5309
Reputation: 365767
When you use a relative path, like this:
open('file/path/file_name', 'w')
That's equivalent to taking the current working directory, appending /file/path/file_name
, and trying to open or create a file at that location.
So, if there is no file
directory under the current working directory, or there is a file
directory but it has no path
directory underneath it, you will get this error.
If you want to create the directory if it doesn't exist, then create the file underneath it, you need to do that explicitly:
os.makedirs('file/path')
open('file/path/file_name', 'w')
For debugging cases like this, it may be helpful to print out the absolute path to the file you're trying to open:
print input
print os.path.abspath(input)
This may be, say, /home/root/file/path/file_name
. If that was what you expected, then you can check (in your terminal or GUI) whether /home/root/file/path
already exists. If it wasn't what you expected, then your current working directory may not be what you wanted it to be.
Upvotes: 4