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

Albert-Jan Roskam fomcl at yahoo.com
Fri Aug 1 22:23:08 CEST 2014




------------------------------
On Fri, Aug 1, 2014 12:35 AM CEST Steven D'Aprano wrote:

>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'])

Won't that write the mp3 to the current working dir? (Is that the dir where the .py lives? Or even the Python bin dir? Perhaps the cwd parameter of call() will be good?


More information about the Tutor mailing list