Python Forum
Escaping whitespace and parenthesis in filenames - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Escaping whitespace and parenthesis in filenames (/thread-9100.html)



Escaping whitespace and parenthesis in filenames - jehoshua - Mar-21-2018

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.html#shlex.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.


RE: Escaping whitespace and parenthesis in filenames - Gribouillis - Mar-21-2018

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)



RE: Escaping whitespace and parenthesis in filenames - jehoshua - Mar-21-2018

(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)