Python Forum
Escaping whitespace and parenthesis in filenames
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Escaping whitespace and parenthesis in filenames
#3
(Mar-21-2018, 06:47 AM)Gribouillis Wrote: Use .....

Thanks, that works just fine on whitespaces, left and right parenthesis and left and right square brackets.

#!/usr/bin/python3

import re
import glob, os

os.chdir("/home/somepath")

_to_esc = re.compile(r'\s|[]()[]')

def _esc_char(match):
    return '\\' + match.group(0)
 
def my_escape(name):
    return _to_esc.sub(_esc_char, name)
 
for file in glob.glob("chunk*.txt"):
    file = my_escape(file)
    print(file)
Reply


Messages In This Thread
RE: Escaping whitespace and parenthesis in filenames - by jehoshua - Mar-21-2018, 09:12 AM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Next/Prev file without loading all filenames WilliamKappler 9 506 Apr-12-2024, 05:13 AM
Last Post: Pedroski55
  Very simple question about filenames and backslashes! garynewport 4 1,933 Jan-17-2023, 05:02 AM
Last Post: deanhystad
  select Eof extension files based on text list of filenames with if condition RolanRoll 1 1,515 Apr-04-2022, 09:29 PM
Last Post: Larz60+
  Why does Python not use parenthesis to contain loops? davidorlow 3 3,480 Jun-09-2021, 06:33 AM
Last Post: Gribouillis
  Style question on adherence to PEP 8 with whitespace near an "=" sign nilesh 6 3,944 Jan-12-2021, 11:11 PM
Last Post: snippsat
  Introduction to escaping characters in strings Geelong_crazy 1 2,857 Jul-18-2020, 06:58 PM
Last Post: DT2000
  Superfluous whitespace found? CaptainCsaba 2 21,248 Mar-19-2020, 09:04 AM
Last Post: ak52
  Escaping '$' in pymongo raulp2301 0 1,640 Feb-14-2020, 03:48 PM
Last Post: raulp2301
  Getting a list of filenames in a directory DavidHT 2 8,299 Feb-03-2020, 06:56 AM
Last Post: DavidHT
  How to double quote filenames (spaces)? Winfried 2 3,479 Jan-25-2020, 09:39 PM
Last Post: Winfried

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020