I don't use IDLE except for very elementary code, it has issues you should look to use a different IDE, there are many available, and your choice will be made after trying a few out.
Many of the staff here use VSCode (not to be confused with Visual Studio). It's free, and easy to use.
I use the following statement at the start of each module in my project.
os.chdir(os.path.abspath(os.path.dirname(__file__)))
It sets the starting point for every node of my directory tree. (script directory as base.
once set, I then have a model that has the tree structure (relative to my src directory) for the entire projrct
which looks similar to:
PathTree.py
import os
from pathlib import Path
class PathTree:
def __init__(self):
os.chdir(os.path.abspath(os.path.dirname(__file__)))
homepath = Path('.')
rootpath = homepath / '..'
self.docpath = rootpath / 'doc'
self.docpath.mkdir(exist_ok=True)
self.datapath = rootpath / 'data'
self.datapath.mkdir(exist_ok=True)
self.databasepath = self.datapath / 'database'
self.databasepath.mkdir(exist_ok=True)
self.excelpath = self.datapath / 'excel'
self.excelpath.mkdir(exist_ok=True)
self.csvpath = self.datapath / 'csv'
self.csvpath.mkdir(exist_ok=True)
self.htmlpath = self.datapath / 'html'
self.htmlpath.mkdir(exist_ok=True)
self.imagepath = self.datapath / 'images'
self.imagepath.mkdir(exist_ok=True)
self.jsonpath = self.datapath / 'json'
self.jsonpath.mkdir(exist_ok=True)
self.logpath = self.datapath / 'logs'
self.logpath.mkdir(exist_ok=True)
self.pandaspath = self.datapath / 'pandas'
self.pandaspath.mkdir(exist_ok=True)
self.prettypath = self.datapath / 'pretty'
self.prettypath.mkdir(exist_ok=True)
self.tmppath = self.datapath / 'tmp'
self.tmppath.mkdir(exist_ok=True)
# urls:
self.AmericasStockExchanges = "https://en.wikipedia.org/wiki/List_of_stock_exchanges_in_the_Americas"
self.ASE_savefile = self.htmlpath / "AmericasStockExchanges.html"
if __name__ == '__main__':
PathTree()
to use, simply import the module and create an instance
example:
try_pathtree.py
from PathTree import PathTree
import requests
class MyClass:
def __init__(self):
self.ptree = PathTree()
def Do_something(self):
response = requests.get(self.ptree.AmericasStockExchanges)
if response.status_code == 200:
with self.ptree.ASE_savefile.open('wb') as fp:
fp.write(response.content)
else:
print(f"Unable to load URL: {self.ptree.AmericasStockExchanges}")
def main():
mc = MyClass()
mc.Do_something()
if __name__ == '__main__':
main()
so, the first time PathTree is imported, it will create the directory structure if it's not already there, or if new directories need to be created.
usage is simple, and when you add a new node (directory) to the PathTree, every module in your project will immediately have access to that node.