Reputation: 17
I am trying to learn the file I/O in python, I am trying following code to generate a text file in D drive of my computer with the statements written in the code but the compilation fails saying that the file 'I want to create' is not available which is obvious. How to create the file then?
file = open(r'D:/pyflie/text.txt',"w")
file.write("Hello World")
file.write("This is our new text file")
file.write("and this is another line.")
file.write("Why? Because we can.")
file.close()
and the error shown is
C:\Users\ssgu>python D:/pyfile/fw.py
Traceback (most recent call last):
File "D:/pyfile/fw.py", line 1, in <module>
file = open(r'D:/pyflie/text.txt',"w")
FileNotFoundError: [Errno 2] No such file or directory:
'D:/pyflie/text.txt'
Upvotes: 0
Views: 1240
Reputation: 16633
You will get such an error if one of the specified directories does not exist. In this case, D:/pyflie/
does not exist yet, so it must be created beforehand. Then, your code should create and open the file normally. You can check upfront:
import os
if not os.path.exists(r"D:\pyflie"):
os.makedirs(r"D:\pyflie")
file = open(r'D:\pyflie\text.txt',"w")
file.write("Hello World")
file.write("This is our new text file")
file.write("and this is another line.")
file.write("Why? Because we can.")
file.close()
Also, check for typos in the path name. Did you mean D:/pyfile/
?
Upvotes: 2