Home > Software engineering >  Why does Python not find/recognise a file saved in the same directory as the file where the code is
Why does Python not find/recognise a file saved in the same directory as the file where the code is

Time:04-10

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.

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?

CodePudding user response:

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 '...'.

CodePudding user response:

It depend from where the python command is launched for instance : let suppose we have this 2 files :

  • dir1/dir2/code.py <- your code
  • dir1/dir2/test.txt if you run your python commande from the dir1 directory it will not work because it will search for dir1/test.txt

you need to run the python commande from the same directory(dir2 in the example).

  • Related