1

I have a folder that has a mix and match of camelCase and non camel case filenames. I have used this in Python to remove underscores and was hoping I could easily tweak it to replace 'camelCaseExample' with 'camel Case Example':

folder = r"C:/....."
import os
pathiter = (os.path.join(root, filename)
    for root, _, filenames in os.walk(folder)
    for filename in filenames
)
for path in pathiter:
    newname =  path.replace('_', ' ')
    if newname != path:
        os.rename(path,newname)

Could anyone help me edit this to get it working for regex?

I have tried this with no luck:

newname =  path.replace('%[A-Z][a-z]%', ' ')

I would also be able to use a c# solution if that would be easier

SCB
  • 5,821
  • 1
  • 34
  • 43
user3486773
  • 1,174
  • 3
  • 25
  • 50
  • Why do you have `%` in your regex? – Galen Dec 22 '17 at 03:06
  • I must be thinking of SQL. I have tried it without and still no luck. – user3486773 Dec 22 '17 at 03:07
  • 2
    If your goal is to simply replace insert a space between a lowercase alpha followed by an uppercase alpha: `re.sub(r'([a-z])([A-Z])', r'\1 \2', 'camelCaseExample')`. See [`re.sub`](https://docs.python.org/3/library/re.html#re.sub) – Galen Dec 22 '17 at 03:10
  • the issue is when I try to do this with folders, as this seems to apply this to the entire path rather than filename? – user3486773 Dec 22 '17 at 03:21
  • So only apply it to the filename. You are currently joining the filename with the root immediately. – Galen Dec 22 '17 at 03:26

1 Answers1

2

You will probably want to try regex using the re library.

import re
new_name = re.sub("(?=[A-Z])", " ", "testFileName")
print(new_name)

Will output:

test File Name

If you want it to be lowercase after this, you could just call

new_name = new_name.lower()

What the regex is doing is looking for any point immediately before an upper case letter and substituting a space there. This regex101 link will help explain it better.

SCB
  • 5,821
  • 1
  • 34
  • 43
  • This applies the logic to the entire path, rather than just the filename. It also adds a space between words, so it converts 'This File' to 'This File'. Which creates issues with the entire path. – user3486773 Dec 22 '17 at 03:24
  • How did you handle that in your original underscore version? – SCB Dec 22 '17 at 03:25
  • Something like [`os.path.basename()`](https://docs.python.org/3/library/os.path.html#os.path.basename) might be helpful for you. – SCB Dec 22 '17 at 03:26
  • the underscore was only part of filename, and never anywhere upstream in path, so was a non issue. – user3486773 Dec 22 '17 at 03:27
  • Yup that was it. THANK YOU! – user3486773 Dec 22 '17 at 03:39