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
#1
I need to write a small script that creates 'ffmpeg' code and therefore need to escape whitespaces and parenthesis in the filenames.

Have looked at a few ways to do this and keep getting errors. Here is what I have tried

https://docs.python.org/3/library/shlex....hlex.quote

https://pypi.python.org/pypi/shellescape

This doesn't quite do what I wanted:

#!/usr/bin/python3

import re
import glob, os

for file in glob.glob("chunk*.txt"):
    print(re.escape(file))
Where the filename is chunk-the quick brown (fox) jumped.txt the output is
Output:
chunk\-the\ quick\ brown\ \(fox\)\ jumped\.txt
Where the filename is chunk-182.txt the output is
Output:
chunk\-182\.txt
I don't need the dashes or periods escaped, only whitespace, parenthesis and square brackets.
Reply
#2
Use
import re
_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)

# file = my_escape(file)
Reply
#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


Possibly Related Threads…
Thread Author Replies Views Last Post
  Very simple question about filenames and backslashes! garynewport 4 1,830 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,475 Apr-04-2022, 09:29 PM
Last Post: Larz60+
  Why does Python not use parenthesis to contain loops? davidorlow 3 3,399 Jun-09-2021, 06:33 AM
Last Post: Gribouillis
  Style question on adherence to PEP 8 with whitespace near an "=" sign nilesh 6 3,848 Jan-12-2021, 11:11 PM
Last Post: snippsat
  Introduction to escaping characters in strings Geelong_crazy 1 2,794 Jul-18-2020, 06:58 PM
Last Post: DT2000
  Superfluous whitespace found? CaptainCsaba 2 21,174 Mar-19-2020, 09:04 AM
Last Post: ak52
  Escaping '$' in pymongo raulp2301 0 1,608 Feb-14-2020, 03:48 PM
Last Post: raulp2301
  Getting a list of filenames in a directory DavidHT 2 6,936 Feb-03-2020, 06:56 AM
Last Post: DavidHT
  How to double quote filenames (spaces)? Winfried 2 3,414 Jan-25-2020, 09:39 PM
Last Post: Winfried
  CSV file escaping characters lokhtar 2 2,627 Dec-09-2019, 06:48 PM
Last Post: lokhtar

Forum Jump:

User Panel Messages

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