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

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

Asked 8 months ago
4
4 answers

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

Source: link

0

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

Source: link

0

mimetype gives the same result for both files:
$ mimetype *.py
buy_test.py:         text/x-python
candlestick_test.py: text/x-python
file -i gives different outputs:
$ file -i buy_test.py 
buy_test.py: text/x-python; charset=us-ascii
$ file -i candlestick_test.py 
candlestick_test.py: text/x-objective-c; charset=us-ascii
But the answer he got, doesn't work for me:
$ grep -r 'text/x-python' /usr/share/thumbnailers
I think the main diffenrence between these python files is the shebang:
$ head -n2 buy_test.py 
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
$ head -n2 candlestick_test.py 
# -*- coding: utf-8 -*-
"""
When I use this shebang (python 2) ...
#!/usr/bin/env python

Source: link

0

To illustrate standard import usage, let's say we create a file called mymodule.py with the following function definition:
def say_hello():
   print( 'Hello, world!' )
1
2
1 2
def say_hello():
   print( 'Hello, world!' )
To call say_hello() from inside script.py, we can write in script.py:
import mymodule

mymodule.say_hello()
1
2
3

Source: link

Recent Questions on python

    Programming Languages