skushu
skushu

Reputation: 321

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

The file "test_text.txt" is in the same folder as the program. it's a seperate folder from everything else that just has the text file and the program. unless I am misunderstanding what the error means, I just can't figure out what i'm missing or did wrong. i'm just reading a basics python book and this I pretty much copied it 1 for 1.

CODE

with open('test_text.txt') as test_text:
    reader = test_text.read()
    print (reader)

Upvotes: 0

Views: 19564

Answers (3)

Bearded Daddy
Bearded Daddy

Reputation: 1

Thank you Pointman for your answer. It did not work for me but it did lead me to what worked. I am using Visual Studio Code and I was having this issue with opening a text from a Udemy course.

jabber = open('Jabberwocky.txt', 'r')

for line in jabber:
    print(line)
    
jabber.close()

After running this code I would get the following error message

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

I tried both the absolute path and the relative path option but they did not work for me. What I found that worked was once the terminal is open using Python you will have to traverse through your files until you get to the said folder or file. Once you do this then run the code and it will work.

Upvotes: 0

P0intMaN
P0intMaN

Reputation: 134

FileNotFoundError occurs when you are trying to access files outside the scope of the application. In this case, the scope of your application is the folder in which you main python file resides.

There are couple of ways through which you can resolve this:

1. Provide an absolute or full path to the file: As mentioned by @pigeonburger in his answer, you can provide a full path. If you are using windows, then full path will be from C:/Desktop/

2. Using a Relative Path: Relative paths is the solution if both the file you want to access and the python program are in the same folder. Relative Paths start with ./ So, based on your file structure, the possible solution is this:

with open('./test_text.txt'):
  # your code

Upvotes: 0

pigeonburger
pigeonburger

Reputation: 736

FileNotFoundError means you are trying to open a file that does not exist in the specified directory (in this case, whatever directory you are running your Python script from).

the file "test_text.txt" is in the same folder as the program. it's a seperate folder from everything else that just has the text file and the program

In that case, you need to make sure that you're in the same directory as your file on your command-line, or specify the full path to test_text.txt (e.g. /home/user/Desktop/test_text.txt)

Upvotes: 3

Related Questions