Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 "'"

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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("'", "")
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading