Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to deal with multiple dots in a file name with Python pathlib?

I am having an issue with pathlib when I try to construct a file path that has a "." in its name, the pathlib module ignores it.

Here are example lines (I tried multiple versions, all resulted the same issue)

The issue is that the original file name will be coming from another application, so it is not like I can edit the name myself. I also do not want to do string replacement work arounds, if possible.

path=r"c:\temp"

1

p=Path(path).joinpath("myfile.001").with_suffix(".bat")

2

p=Path(path, "myfile.001").with_suffix(".bat")

3

p=Path(path).with_name("myfile.001").with_suffix(".bat")

All these lines will yield to

WindowsPath('C:/temp/myfile.bat')

So how do I make pathlib.Path to construct this full path properly. The final path has to be

WindowsPath('C:/temp/myfile.001.bat')

Not

WindowsPath('C:/temp/myfile.bat')

Naturally I am looking for a way to do it through pathlib itself, otherwise I can just use os.

thanks

like image 720
yarun can Avatar asked Jan 24 '19 22:01

yarun can


People also ask

What does Pathlib path do in Python?

Fortunately, if you're coding in Python, the Pathlib module does the heavy lifting by letting you make sure that your file paths work the same in different operating systems. Also, it provides functionalities and operations to help you save time while handling and manipulating paths.

How do I get the Basename of a file in Python?

path. basename() method in Python is used to get the base name in specified path.

Is Pathlib path PathLike?

Path (WindowsPath, PosixPath, etc.) objects are not considered PathLike.


1 Answers

You are telling pathlib to replace the suffix .001 with the suffix .bat. pathlib complies.

Tell pathlib to add .bat to the existing suffix.

p = Path(path, 'myfile.001')
p = p.with_suffix(p.suffix+'.001')
like image 171
user2357112 supports Monica Avatar answered Oct 15 '22 16:10

user2357112 supports Monica