Reputation: 1626
I am trying to create a text file using python. Here is my code-
import sys
import os
str1="a1.txt"
file1="Documents/Inbox/"
completeName=file1+str1
name1=os.path.abspath(completeName)
myfile = open(name1, 'w')
I want to save file a1.txt
in my documents folder in my home directory.I get the following error using above code-
Traceback (most recent call last):
File "filesave.py", line 8, in <module>
myfile = open(name1, 'w')
FileNotFoundError: [Errno 2] No such file or directory: '/home/pulkit/Documents/Documents/Inbox/a1.txt'
Upvotes: 1
Views: 3149
Reputation: 1074
This code shows you how to check the path exists and expand ~
to access home directory of the user running the script.
#!/usr/bin/python
import os
dpath=os.path.join(os.path.expanduser("~"),"Documents","Inbox")
if not os.path.exists(dpath):
os.makedirs(dpath)
fpath=os.path.join(dpath,"a1.txt")
open(fpath,"w").write("what ever you want")
Upvotes: 3
Reputation: 11134
See the error
FileNotFoundError: [Errno 2] No such file or directory: '/home/pulkit/Documents/Documents/Inbox/a1.txt'
Clearly, the path evaluated is:
/home/pulkit/Documents/Documents/Inbox/a1.txt
But you have,
/home/pulkit/Documents/Inbox/a1.txt
So, change file1="Documents/Inbox/"
to file1="Inbox/"
Upvotes: 0
Reputation: 189487
os.path.abspath()
does not know which directory you want the file to exist in -- it simply uses the current directory, which seems to have been $HOME/Documents
when you got the backtrace.
Either
Upvotes: 2
Reputation: 86
In your case omit the 'Documents/' from your variable file1 setting like:
file1="Inbox/"
Upvotes: 0