1

I've searched and cannot find how to fix this. I am watching a tutorial and I created a file called "testfile" in notepad. It's a .txt file. When I type

file1 = open("testfile.txt", "r") 

in to python I get this error:

FileNotFoundError: [Errno 2] No such file or directory: 'testfile.txt'

What can I do to fix this? Thanks!

Van Peer
  • 2,127
  • 2
  • 25
  • 35

4 Answers4

0

Are they in the same directory? The testfile.py and your python code need to be in the same directory to be able to find the file. Otherwise, testfile needs to have its path specified.

clemens
  • 16,716
  • 11
  • 50
  • 65
0

This is a problem with the path. I assume your file testfile.txt is located in the same directory where you run your script, called the working directory. Please, try ./testfile.txt. This should work.

clemens
  • 16,716
  • 11
  • 50
  • 65
0

Try giving out the entire location of the file like on desktop or the C drive wherever that is, E.g.: c:\users\desktop\testfile

clemens
  • 16,716
  • 11
  • 50
  • 65
sreemaan
  • 1
  • 1
-1

Make sure that the file "testfile.txt" is in the same folder as your running code. Then code like this will work:

with open("testfile.txt","r") as fileTest:
    rawLines = fileTest.readlines()

Oh, and by the way, nice username.

JimmyCarlos
  • 1,934
  • 1
  • 10
  • 24
  • 2
    It needs to be not the same folder *as the running code*, but the same folder *that is the current working directory of the user who's running the code*. If I'm in the directory `/foo` and run `python /bar/some.py`, and that script tries to open `hello.txt`, it'll be looking for `/foo/hello.txt`, not `/bar/hello.txt`. – Charles Duffy Jul 22 '19 at 19:43