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

Why does Python not find/recognise a file saved in the same directory as the file where the code is written?

I am quite new to working with Python files, and having a small issue. I am simply trying to print the name of a text file and its 'mode'.

Here is my code:

f = open('test.txt','r')

print(f.name)
print(f.mode)

f.close() 

I have a saved a text file called 'test.txt' in the same directory as where I wrote the above code.

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

However, when I run the code, I get the following file not found error:

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

Any ideas what is causing this?

I have also tried to replace the first argument above with the path of the test.txt file, but I get the same error?

>Solution :

open (on pretty much any operating system) doesn’t care where your program lies, but from which directory you are running it. (This is not specific to python, but how file operations work, and what a current working directory is.)

So, this is expected. You need to run python from the directory that test.txt is in.


I have also tried to replace the first argument above with the path of the test.txt file, but I get the same error?

In that case, you must have mistyped the path. Make sure there’s no special characters (like backslashes) that python interprets specially in there, or use the raw string format r'...' instead of just '...'.

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