Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Dir Ops
#1
I have spent hours today searching for something which *should*n be utterly simple.
It is simply putting the current working directory into a variable so that it could be manipulated as part of a renaming process. Finally, it is:

currdir = os.path.split(os.getcwd())[1]
print(currdir)

My first question is: Is there anything simpler? Without the baggage of walking to root.
something like os.path.just_this_dir?

My next question is the nature of the shutil.move statement.
would somethinmg like:
newdir = re.sub(r'('_'),(' '),currdir)
shutil.move(currdir,newdir)
work?

In Perl direcotiries are moved the same way as files. And move is also used in renaming.

One of the issue I am having is that in Python, os ops functions do not seem to recognize the . operator as current dir. Or at least the way i tried it.

I can, of course 'join' to the parent directories to get an absolute path for file/dir operations, but would prefer a simpler mechanism as the moves I will be doing are pretty much all relative to the current dir.

In other words, is:
shutils.move(./foo,./bar)
kosher?
Reply
#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
#3
Yes!! Quite what I am looking for, and I definitely need to study pathlib.

Query: The raw ' / ' looks perplexing. Do I need to 'join' it for system compatibility? (I switch between Linux and Win7)
self.datapath = self.project_home / 'data'
In my use I would probably set the default path to '.'

def project(self):
# To create a file in datapath
project_data_file = self.datapath / 'MyData.zig'
Does this 'touch' MyData.zig? (Create an empty file?)

Update: in going through the pathlib docs (in Win for now)

>>> from pathlib import PurePath
>>> PurePath('foo', 'some\path', 'bar')
PureWindowsPath('foo/some/path/bar')

But.. 'Pure' win format is giving Posix dir seperators????

Dont understand resolve here. The FAQ is confusing on this issue. I assume it is the same as os.path.abspath?
Reply
#4
Quote:Query: The raw ' / ' looks perplexing. Do I need to 'join' it for system compatibility?

This is the way I saw new ubdirectories defined when pathlib first arrived, so have followed it ever since (for pathlib only) I like it because it makes these directory definitions stand out.

Quote:The FAQ is confusing on this issue. I assume it is the same as os.path.abspath?
I agree with the confusion, pathlib is a pure object, In the beginning, the 'posix' tag bothered me, and still causes some quirks, for example when trying to save a posix path in a json document (it can be done, ironically by using os.fspath). I accept that because of the utility offered by the pathlib object.

read this: https://realpython.com/python-pathlib/ it may make you more comfortable with the command.
also this: https://treyhunner.com/2018/12/why-you-s...g-pathlib/
and this: https://treyhunner.com/2019/01/no-really...-is-great/
Reply
#5
Tahnks again.
My paranoia has abated somewhat when hacking away at a textbook example and a google generator:

import shutil
import os

def char_range(c1, c2):
    """Generates the characters from `c1` to `c2`, inclusive."""
    for c in range(ord(c1), ord(c2)+1):
        yield chr(c)

BASE_PATH = '00TEST'  # this will be our base path
os.mkdir(BASE_PATH)

for c in char_range('A', 'Z'):
    path_b = os.path.join(BASE_PATH, c )
    os.makedirs(path_b)
While using os instead of pathlib, it geberates alphabet dirs (which have a real use here), and without any gotchas.

Need to go study ord, to make sense of the function...
Reply


Forum Jump:

User Panel Messages

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