0

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' 
3
  • 2
    pyflie looks like a typo. I suppose it should be pyfile. Commented Nov 25, 2018 at 10:18
  • You have a typo in your file = open(r'D:/pyflie/text.txt',"w"). Should be pyfile Commented Nov 25, 2018 at 10:18
  • @mzjn yes, it was a typo, I will be careful from next time. Thanks Commented Nov 25, 2018 at 10:35

1 Answer 1

2

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/?

Sign up to request clarification or add additional context in comments.

2 Comments

I hope you don't mind the edit ;) your answer is right...he needs to check first
The directory could be created in the program, as opposed to manually, using os.mkdir() or os.makedirs().

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.