Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to fix FileNotFoundError?

I have encountered a problem while trying to open a .txt file from the same directory where my source code is located.
When I tried to open the file like this:

with open("pi_digits.txt") as file_object:
        contents = file_object.read()
print(contents)

I failed.
I also failed when I typed the whole path:

with open("Users\lukas\Documents\python_work\chapter_10") as file_object:
        contents = file_object.read()
print(contents)

But when I typed:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

with open("\\Users\\lukas\\Documents\\python_work\\chapter_10\\pi_digits.txt") as file_object:
    contents = file_object.read()
print(contents)

I succeeded!

So my question is: Why can’t I run the code without error when I enter the following code:

with open('pi_digits.txt') as file_object:
    contents = file_object.read()
print(contents)

Thank you for your answers and sorry if my question was not well constructed.

>Solution :

@Sottvogel

In general, a python instance can be run from many different directories in your computer. One way to check where the running instance is:

import os 
os.getcwd()

If you confirm that you are in the same directory of your file, try and see
what the following returns:

os.listdir()

In case your file doesn’t appear in the returned string, then there has to be another problem. Make sure you checkout the docs as well.

Hope it helps!

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading