Friday 29 May 2015

Python - Finding an Item Between Two Characters In a String Using: partition and rpartition

I'm making a file saver at the moment and I need a little control over the location of the saved files so I can't use Python's handy tkFileDialog to save the file. This means I have to create my own file saver.

Problem

One of the problems my file saver might face is: what happens if a user chooses a file name that already exists. I'll have to rename the file.
So for example if the user creates a filename: batman.jpg. And a batman.jpg file already exists in the folder. Then I don't want to overwrite it. I want to give it the value: batman(1).jpg. Okay that is pretty easy to fix. Run a file search
But what if the user os.path.isfile search then and an if statement asking if the file exists. if it does:

All sorted.
But what if our user is the Hordor of Batman fans and wants to save every file as batman.jpg. We then I need a to run a for loop to search through the folder for batman(1)jpg, batman(2).jpg ... batman(x).jpg and then save it as the next number.

But how do I isolate the number?

Solution

Enter Pythons partition and rpartition. I need to get between the two brackets. I can use partition  split the string at the first bracket keeping everything after the occurrence. Then I can use rpartition to split the string at the last bracket keeping everything before the occurrence. Take a look at the example below:

No comments:

Post a Comment