0

I am trying to open a file with python like this:

m = open("e.txt", 'r')

The text file I'm trying to open is in the same directory as my python file is. However I'm getting an error message.

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

I've also tried using:

import os
cwd = os.getcwd() # cwd: current working directory
path = os.path.join(cwd, "e.txt")

The error message looks a little different this time:

FileNotFoundError: [Errno 2] No such file or directory: 'C:\\Users\\user\\e.txt'

I hope someone can help me with this issue. Thanks in advance.

9
  • hello @gamer_294 , I think you need to change it like tihs m = open("e.txt", 'r') Commented Jan 4, 2021 at 11:06
  • The file needs to be in the directory from where you call the script, not the directory where the script exists. Commented Jan 4, 2021 at 11:07
  • 1
    @IceBear yes I'm sorry it is like that I will edit my question. Commented Jan 4, 2021 at 11:07
  • Sorry, I don't see your issue. Either you have the file present, in which case you won't get an exception, or the file is not present in which case you will get the exception. Either way, in general, you need to handle both cases. Commented Jan 4, 2021 at 11:07
  • 2
    @Djib2011 Thank you, that helped. But please avoid answering questions in comments and write an answer instead. Commented Jan 4, 2021 at 11:13

2 Answers 2

0

The could be in a folder, if this is the case then the full name has to be written. Such as:

m = open("E://folder/e.txt","r")
print(m.read())

It is important to write the EXACT directory of the file.

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

1 Comment

I used a relative pathname and after the failed attempt I tried using the absolute one with os.path.join.
0

The code is perfectly correct. Check the type of file whether it is .txt or some other file. If everything is correct you should check the location you gave

2 Comments

As I said I am 100% sure the location I gave is accurate.
Then u have to check the type (file extension) of file and where your python script is...

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.