[Tutor] Using subprocess on a series of files with spaces

Steven D'Aprano steve at pearwood.info
Fri Aug 1 00:35:34 CEST 2014


You may have already have solved your problem, unfortunately my 
emails are coming in slowly and out of order, but I have a suggestion:

On Thu, Jul 31, 2014 at 03:53:48PM -0400, C Smith wrote:
> I am on OSX, which needs to escape spaces in filenames with a backslash.

Same as any other Unix, or Linux, or, indeed, Windows.

> There are multiple files within one directory that all have the same
> structure, one or more characters with zero or more spaces in the
> filename, like this:
> 3 Song Title XYZ.flac.
> I want to use Python to call ffmpeg to convert each file to an .mp3.
> So far this is what I was trying to use:
> import os, subprocess
> track = 1
> for filename in os.listdir('myDir'):
>     subprocess.call(['ffmpeg', '-i', filename, str(track)+'.mp3'])
>     track += 1

I believe that your problem is *not* the spaces, but that you're passing 
just the filename and not the directory. subprocess will escape the 
spaces for you. Also, let Python count the track number for you. Try 
this:


directory = '/path/to/the/directory'
for track, filename in enumerate(os.listdir(directory), 1):
    pathname = os.path.join(directory, filename)
    subprocess.call(['ffmpeg', '-i', filename, str(track)+'.mp3'])


I expect something like that will work. You should be able to pass 
either an absolute path (beginning with /) or a relative path starting 
from the current working directory.

If this doesn't work, please show the full error that you receive. If it 
is a Python traceback, copy and paste the whole thing, if it's an ffmpeg 
error, give as much information as you can.



-- 
Steven


More information about the Tutor mailing list