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.

gamer_294
  • 13
  • 4
  • hello @gamer_294 , I think you need to change it like tihs `m = open("e.txt", 'r')` – Ice Bear Jan 04 '21 at 11:06
  • The file needs to be in the directory **from where you call the script**, not the directory where the script exists. – Djib2011 Jan 04 '21 at 11:07
  • 1
    @IceBear yes I'm sorry it is like that I will edit my question. – gamer_294 Jan 04 '21 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. – quamrana Jan 04 '21 at 11:07
  • @gamer_294 , may I ask if you really do have a `"e.txt"` on your directory? cause if not I think you need to have it when you run your program cause with the second param `'r'` says `read`. Thanks! – Ice Bear Jan 04 '21 at 11:09
  • 2
    @Djib2011 Thank you, that helped. But please avoid answering questions in comments and write an answer instead. – gamer_294 Jan 04 '21 at 11:13
  • @IceBear I am 100% sure the file exists. – gamer_294 Jan 04 '21 at 11:14
  • @gamer_294 I like your comment :) – Ice Bear Jan 04 '21 at 11:59
  • @gamer_294 I'm glad it helped, I wasn't sure if that would answer your question or you might have another issue, so I refrained from making an answer. – Djib2011 Jan 04 '21 at 13:58

2 Answers2

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.

mullena
  • 58
  • 1
  • 8
  • I used a relative pathname and after the failed attempt I tried using the absolute one with `os.path.join`. – gamer_294 Jan 05 '21 at 03:19
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