Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Dir Ops
#2
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:
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
Reply


Messages In This Thread
Dir Ops - by millpond - Sep-10-2019, 02:56 AM
RE: Dir Ops - by Larz60+ - Sep-10-2019, 10:52 AM
RE: Dir Ops - by millpond - Sep-11-2019, 02:23 AM
RE: Dir Ops - by Larz60+ - Sep-11-2019, 11:53 AM
RE: Dir Ops - by millpond - Sep-14-2019, 05:09 AM

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020