[Solved] Open a File in Python

When i follow the instructions for the exercise “Opening a File in Python” as given at:

i get the FileNotFoundError: [Errno 2]

My .txt file to open is in the same directory as the .ipynb (Python) file.
Probably there are some problems with the permissions or something. How could we Solve this?

Reading from file with python

Usefull link about in- and outputs in Python 3

The best practice here is to use “With open file” so you won’t have to bother about closing files and error handling.

# Read the whole file in a string
with open('test.txt', 'r') as f:
    data = f.read()

# Or put the lines in a list
with open('test.txt', 'r') as f:
    data = f.read().splitlines()

You could also use f.readline() to read

Not worth reading, still here for reference.

Thanks for your question. Can you be more specific?

  • what is your os / anaconda version
  • what is the exact code you are trying to run?
  • what is the content of your file?


  • from what folder are you trying to run your code?
  • can you make a screenshot of the Jupyter file list like below?

My steps to reproduce

Create file “test.txt” with some random content in the same directory as the Jupyter Notebook file

Python code in Jupyter Notebook:

f = open("test.txt","r") #opens file with name of "test.txt"


Output when running the code:

If you provide the details as requested above I might be able to help you out.


Thanks for the quick reply.

  • i use the versions: anaconda 4.4.0 and python 3.6.1 on my windows 10
  • The code i try to run is directly copied out of the excersize:

Here is the file “.txt” file located, in the same folder:
(the checked boxes are the ones i used)

Although this time i figured out why i got the error. It’s because i deleted the “.txt” at the filename by changing it.

But now as shown, i don’t get any print results.
Also the f.readline() command doesn’t work.
This time i’m sure the link works because of no errors.

So again is something weird going on here.

Would you mind sharing the content of test.txt? :smile:

edit: I tested with a space in the folder name, and that doesn’t make a difference here. Everything is still working as expected. Can’t seem to reproduce your problem so far.

The content was like you wrote.
Probably the edited .txt file (with content) wasn’t saved before i ran the program.
So the saved (default) version i wanted to open was ofcourse empty.
I tried to run the program a couple minutes later and now the .txt was autosaved which made the program run.
My problem is solved!

Thanks for your help