Sep-10-2019, 10:52 AM
If directory structure is setup using pathlib instead of os, then you don't have a need to save in a variable.
I still use os once in my program to set a starting directory and then set all other directories relative to that.
example:
I still use os once in my program to set a starting directory and then set all other directories relative to that.
example:
class MyPths: def __init__(self): # Anchor starting path os.chsir(os.path.abspath(os.path.dirname(__file__))) self.srcpath = Path('.') self.project_home = self.srcpath / '..' self.datapath = self.project_home / 'data' def project(self): # To create a file in datapath project_data_file = self.datapath / 'MyData.zig' # Once defined, you can now do many things: # To open datafile: with project_data_file.open() as fp: zingo = fp.read() # to create a new directory in datapath mynewdir = self.datapath / 'mynewdir' # create it if it doesn't already exist mynewdir.mkdir(exist_ok=True) # display filename: print(mynewdir.name) # get absolute path print(mynewdir.resolve()) # get list of files in datapath print([filenames for filenames in mynewdir.iterdir() if filename.is_file()]) # or to save filelist = [filenames for filenames in mynewdir.iterdir() if filename.is_file()] # get a list of directories in datapath dirs = [dirnames for dirnames in self.datapath.iterdir() if dirnames.is_dir()] # and much much more, see: https://docs.python.org/3/library/pathlib.html