How to have multiple programs access the same file without manually giving them all the file path? How to have multiple programs access the same file without manually giving them all the file path? tkinter tkinter

How to have multiple programs access the same file without manually giving them all the file path?


If the requirement is to get the most recently modified file in a specific directory:

import osmypath = r'C:\path\to\wherever'myfiles = [(f,os.stat(os.path.join(mypath,f)).st_mtime) for f in os.listdir(mypath)]mysortedfiles = sorted(myfiles,key=lambda x: x[1],reverse=True)print('Most recently updated: %s'%mysortedfiles[0][0])

Basically, get a list of files in the directory, together with their modified time as a list of tuples, sort on modified date, then get the one you want.


It sounds like you're looking for a singleton pattern, which is a neat way of hiding a lot of logic into an 'only one instance' object. This means the logic for identifying, retrieving, and delivering the file is all in one place, and your programs interact with it by saying 'give me the one instance of that thing'. If you need to alter how it identifies, retrieves, or delivers what that one thing is, you can keep that hidden.

It's worth noting that the singleton pattern can be considered an antipattern as it's a form of global state, it depends on the context of the program if this is a deal breaker or not.


To "have python select whatever text file is in the folder", you could use the glob library to get a list of file(s) in the directory, see: https://docs.python.org/2/library/glob.html

You can also use os.listdir() to list all of the files in a directory, without matching pattern names.

Then, open() and read() whatever file or files you find in that directory.