pythonregexdirectoryapostrophe

How to you remove multiple apostrophes from filepaths?


My goal is to remove all the single quotes from all file paths in a directory. Working in Windows.

Preamble code:

import os
import re

directory = "/home/oem/Documents/test"

The following doesn't work. It deletes the entire file containing an apostrophe. Also doesn't work to remove ord and substitute "'"

def remove_non_ascii_1(text):

    return ''.join(i for i in text if ord(i) == 39)

[os.rename(os.path.join(dp, f), remove_non_ascii_1(os.path.join(dp, f))) for dp, dn, filenames in os.walk(directory) for f in filenames]

The following works when there is a single apostrophe (ie. file called crazy'yeah.doc changes to crazyyeah.doc. But it doesn't work when there are multiple apostrophes in the path (ie. crazy'yeah'yeah.doc))

def remove_apstrophes(text):

    return re.sub(r"(^.*)(')(.*$)", r"\1\3", text)


[os.rename(os.path.join(dp, f), remove_apstrophes(os.path.join(dp, f))) for dp, dn, filenames in os.walk(directory) for f in filenames]

I tried adding some more capture groups, but this didn't work - crazy'yeah'yeah.doc remains as is with all apostrophes.

def remove_apstrophes(text):

    return re.sub(r"(^.*)(')?.*(')?.*(')?.*(')?.*(.*$)", r"\1\6", text)

[os.rename(os.path.join(dp, f), remove_apstrophes(os.path.join(dp, f))) for dp, dn, filenames in os.walk(directory) for f in filenames]

Thanks in advance for your time


Solution

  • Unless you want to enforce regex, this code achieves what you're trying to do:

    def remove_apostrophes(text):
        return text.replace("'", "")