-1

I've written a script to open, read, and then close a text file, but I keep getting an error message saying it can't find the file I specify.

I've massively reduced the code but I still get the same error message.

The code:

txt = open("textf.txt", "r")
print(txt.read())
txt.close()

The error message from running the code:

Traceback (most recent call last):
  File "C:\Users\miles\AppData\Local\Programs\Python\Python36-32\openfiles.py", line 1, in <module>
    txt = open("textf.txt", "r")
FileNotFoundError: [Errno 2] No such file or directory: 'textf.txt'
Gino Mempin
  • 12,644
  • 19
  • 50
  • 69
Miles Kent
  • 38
  • 7

1 Answers1

0

It depends where you run your code from.

You can use an absolute path (like c:/path/to/file/textf.txt)

Or you can use

import os
this_dir = os.path.dirname(os.path.abspath(__file__))
print(this_dir)

to check where your code is running, then move your file there.

Or you could add the path where the file is located to the PATH environment variable.

Nimirium
  • 41
  • 1
  • 8
  • 3
    I don't think altering the PATH environment variable would solve the problem. PATH is where the shell will look for executable files. – khelwood Aug 02 '19 at 20:38