Skip to content
Advertisement

Tag: pathlib

How to get relative path given a parent of unknown location with Python’s pathlib?

with pathlib.Path.relative_to we can get relative paths with: But what if i don’t know the exact path of the parent directory (but i do know its name)? for example: Path(“/path/to/foo/bar/thing”) relative to “foo” => PosixPath(‘bar/thing’) Path(“/path/to/foo/bar/thing”) relative to “to” => PosixPath(‘foo/bar/thing’) Path(“/another_path/to/foo/bar/thing”) relative to “foo” => PosixPath(‘bar/thing’) how do i get a relative path relative to an arbitrary parent directory

python Path from pathlib module doesn’t add path separator

I have the following issue using Path from the pathlib library: I have tried with Path itself and manually giving it a path that I know exists: I was wondering why Path doesn’t simply add the backslash at the beginning? Is there a better way to build my path with the needed path separator from a list? I didn’t notice

How to remove a file from Path object in Pathlib module?

I have a Path Object representing C:UsersusersDownloadsimg.jpg. How do I get it so the Path only represents C:UsersuserDownloads? I don’t want to delete the file, but rather go back in the Path object itself. Answer I would utilize the PurePath class within pathlib as follows: This yields: PureWindowsPath(‘C:/Users/users/Downloads’)

How to replace characters and rename multiple files?

I have a bunch of pdf files which has the file name as follows: AuthorA_2014_ This is a good article BIsanotherAuthor_1994_ Gr8 artcle CIsFatherOfB_1994_Minor article but not bad And so on. I would like to change the name of the files to this format: AuthorA2014This is a good article BIsanotherAuthor1994Gr8 artcle CIsFatherOfB1994Minor article but not bad How do I do

How to rename all files to include the directory name?

I’m trying to use a For loop in the code below to go through a list of files and rename them with the file directory’s name. Answer Use pathlib Path.rglob: This is like calling Path.glob() with ‘**/’ added in front of the given relative pattern: .parent or .parents[0]: An immutable sequence providing access to the logical ancestors of the path

Advertisement