0

I would like to create a text file in the same directory with my python file, but instead, I get FileNotFounfError. I thought that if the file doesn't exist, open() should create a new file.

My python file:

with open("test.txt", "w") as f:
    f.write("Test")

But I receive the following message

Traceback (most recent call last):
  File "C:/Users/POPOVA/Desktop/Programming/Algs/Stack Overflow/myAns.py", line 1, in <module>
    with open("test.txt", "w") as f:
FileNotFoundError: [Errno 2] No such file or directory: 'test.txt'

Thank you for help

Andrey Kachow
  • 936
  • 7
  • 22

1 Answers1

2

Change:

with open("test.txt", "w") as f:

To:

with open("test.txt", "w+") as f:

You might want to read this stack overflow question as well. Splecially this comment:

The problem is the directory. Either the script lacks the permissions to create a file in that directory, or the directory simply doesn't exist. open('myfile.dat', 'w') is then enough

Dipen Dadhaniya
  • 4,550
  • 2
  • 16
  • 24