Phyton and files

Hi!
I usually use phyton online but I need to work with files so I downloaded the programme in my computer. I think that in order to use files you have to store them in the same folder where phyton is stored:
image

I did it this way but when I try to use the file:
FileNotFounfError
So, phyton cannot find it.
I’ve used:
hand = open(‘regex_sum_1432265.txt’)
and
hand = open(‘regex_sum_1432265.txt’, “r”)

Any ideas where the problem is?

Hi Izan,

No, you don’t store the file in the same place as the Python
interpreter. That is incorrect.

The easiest way is to store the file in the same place as your python
script, not Python itself.

This is good advice for data files that are associated with a script or module. It’s not enough, however, without also discussing the use of __file__. Normally, a module has a global variable named __file__ that contains the path of the executed file. It isn’t always a full path, so first resolve the full path via os.path.abspath(). Then get the path of the containing folder via os.path.dirname(). For example:

_dir = os.path.dirname(os.path.abspath(__file__))

Use os.path.join() to get the full path of a file in this directory. For example:

filename = os.path.join(_dir, "regex_sum_1432265.txt")

If a script has to open many files relative to the script directory, it may be more convenient to make this the current working directory. For example:

os.chdir(os.path.dirname(os.path.abspath(__file__)))

I sometimes come across advice or casual use in online discussions that confuses the script directory with the current working directory. The two are generally unrelated. One connection between them is that if there’s no main script (e.g. for the REPL shell or a -c command), by default the current working directory is added to sys.path (for use by import statements) as if it’s the ‘script directory’.

izan, the screenshot in your message does not show where Python is stored. It’s a folder of shell links (i.e. “.LNK” files) in the start menu. In particular, it’s a folder in “Microsoft\Windows\Start Menu\Programs”, which is relative to either the current user’s “%AppData%” folder or the system’s “%ProgramData%” folder. A shell link (shortcut) contains a command line to execute and sets the initial working directory, among other things.

By default for an all-users installation, 64-bit Python 3.10 is installed in “%ProgramFiles%\Python310”. By default for a per-user installation, it’s installed in “%LocalAppData%\Programs\Python\Python310”.