Reputation: 1084
I'm running into some difficulties with python. I have a code I'm using in conjunction with ArcGIS that is parsing filenames into a database to return the corresponding unique ID and to rename the folder with this unique ID. It has been working great before, but I need to handle some exceptions, like when the Unique ID already exists within the directory, and when the action has already been completed on the directory. The unique id contains all numbers so I've been trying:
elif re.findall('[0-9]', fn):
Roll = string.join(string, "1")
print (Roll)
os.rename(os.path.join(basedir, fn),
os.path.join(basedir, Roll))
which returns all folders with a unique ID. I just can't figure out how to get a count of the number of times a specific folder name occurs in the directory.
Upvotes: 0
Views: 978
Reputation: 25954
I suspect you're making this way harder on yourself than you need to, but answering your immediate question:
folder_name_to_create = 'whatever'
if os.path.exists(folder_name_to_create):
folder_name_to_create += '_1'
If you are getting name collisions, I suspect you need to look at your "unique" naming algorithm, but maybe I'm misunderstanding what you mean by that.
Upvotes: 1
Reputation: 3975
One way to do it might be the following: Create a dictionary whose keys are your folder names, and the value associated with each key is an integer, the number of occurrences of that name. Each time you process a folder, update the dictionary's keys/values appropriately. After you've added all the folder names in your set, check all the count values in the dictionary, and any time the count is > 1 you know you have a duplicate.
Or, if you need to detect duplicates as you go, just check whether the key already exists. In that case you don't really need the value at all, and you can use a set or list instead of a dict.
You could use collections.Counter
to help you in this. You can see an example usage in this question. It shouldn't be too difficult to adapt that example to your needs.
Hope this helps.
Upvotes: 0