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:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
''' | |
Finding an Item Between Two Characters In a String Using: | |
partition and rpartition | |
This could be handy for file creation and checking. | |
''' | |
file = 'batman(0).jpg' | |
file.partition('(')[-1].rpartition(')')[0] | |
''' | |
RESULT: | |
'0' | |
''' |
No comments:
Post a Comment