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
  Style question on adherence to PEP 8 with whitespace near an "=" sign nilesh 6 355 Jan-12-2021, 11:11 PM
Last Post: snippsat
  Introduction to escaping characters in strings Geelong_crazy 1 538 Jul-18-2020, 06:58 PM
Last Post: DT2000
  Superfluous whitespace found? CaptainCsaba 2 8,322 Mar-19-2020, 09:04 AM
Last Post: ak52
  Escaping '$' in pymongo raulp2301 0 537 Feb-14-2020, 03:48 PM
Last Post: raulp2301
  Getting a list of filenames in a directory DavidHT 2 692 Feb-03-2020, 06:56 AM
Last Post: DavidHT
  How to double quote filenames (spaces)? Winfried 2 813 Jan-25-2020, 09:39 PM
Last Post: Winfried
  CSV file escaping characters lokhtar 2 661 Dec-09-2019, 06:48 PM
Last Post: lokhtar
  parenthesis around a tuple of literals in a for Skaperen 2 623 Aug-25-2019, 03:00 AM
Last Post: Skaperen
  Parenthesis in User-Defined Functions giorgitsu 2 677 Aug-07-2019, 12:56 PM
Last Post: ThomasL
  Whitespace syntax error klp21 1 1,314 May-22-2019, 07:49 AM
Last Post: Gribouillis

Forum Jump:

User Panel Messages

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