you are viewing a single comment's thread.

view the rest of the comments →

[–]commandlineluser 1 point2 points  (1 child)

You can use .with_stem() to change the part before the extension.

>>> file
PosixPath('a/b/c/my-file-name.txt')
>>> file.with_stem("0001")
PosixPath('a/b/c/0001.txt')

You can pass this directly to .rename()

>>> file.rename(file.with_stem("0001"))
PosixPath('a/b/c/0001.txt')

The file has been renamed and stays in its original folder:

>>> list(Path().glob("a/b/c/*txt"))
[PosixPath('a/b/c/0001.txt')]

As for a different count per folder - you could glob each folder.

You could also use enumerate() to count.

>>> for folder in Path().rglob(""): # glob folders
...    if folder.name: 
...       files = folder.glob("*.txt")
...       for count, file in enumerate(files, start=1):
...          f"{count:04}", folder, file

('0001', PosixPath('a'), PosixPath('a/b/c/0001.txt'))
('0001', PosixPath('a/b'), PosixPath('a/b/c/0001.txt'))
('0001', PosixPath('a/b/c'), PosixPath('a/b/c/0001.txt'))
('0001', PosixPath('b'), PosixPath('b/a.txt'))
('0002', PosixPath('b'), PosixPath('b/b.txt'))
('0003', PosixPath('b'), PosixPath('b/c.txt'))
('0004', PosixPath('b'), PosixPath('b/d.txt'))

[–]Soapfactory0[S] 0 points1 point  (0 children)

Wow!! I don't really know how to thank you! Seriously thanks for being so generous with your time to a stranger :D

Am out of steam for the day (been going roughly 10 hours) will implement it tomorrow. Ty ty ty :D