Home > Software design >  Handling quotes and spaces in filenames
Handling quotes and spaces in filenames

Time:11-07

I want to create a Python (3) script that passes files to a Linux shell program. Straightforward enough to do, but I'm not sure how to pass filenames that could contain single- or double-quotes and spaces to the shell. I would presumably need to delimit filenames in case they contain spaces.

I might consider a command string something like f"wc -c '{filename}'", but that would break down if I encounter a filename containing a single quote. Likewise if I delimit with double-quotes and encounter a file containing those.

As something like Bob's "special" file would be a valid ext4 filename, how do I cope with all the possibilities?

CodePudding user response:

As Tim Roberts mentioned in comments, you can use subprocess module to bypass this problem. Here is a short example (assuming you have a list of filenames) for passing a list of filenames to wc -c:

from subprocess import run


# assuming you have got a list of filenames
filenames = ['test.py', "Bob's special file", 'test space.py']
for filename in filenames:
    run(['wc', '-c', filename])

By the way, if you want to use Python to get all filenames under one specific directory, you might consider os.listdir.

  • Related