Question

I am creating a program that appends audio files the user selects together using Sox.

I originally created the program for linux but I am making it compatible with Windows. On windows when I pass the list of files to Sox, the program raises 'The filename, directory name, or volume label syntax is incorrect.'

When I print out the list of files it is C:\\\MyProgram\\\ And So On. How Do I Make The '\\' in the path become '\'?

I'm on windows 8.1, so that may be the problem.

I have tried:

str(nameoffile)

os.path.abspath(nameoffile)

os.path.normpath(nameoffile)

There is a huge list of files and directories, so setting the absolute file of each is not an option, I am using os.path.join() to allow the user to navigate through the folders.

But when I pass the files into the list and then call the list using subprocess.list2cmdline(mylist), it simply raises that error above.

Example:

mydirectory = os.getcwd()

appendlist = list()

appendlist.append("sox")

for x, i in enumerate(self.fileselected): # A List Of Files The User Selected

    directory = chosendirectory

    nextfile = os.path.join(chosendirectory, i)

    appendlist.append(nextfile)

subprocess.call([subprocess.list2cmdline(appendlist)], shell=True)

When os.path.join appends the files....it produces "C:\\\Program\\\file" and then it is converted to str(). The str() reads "C:\\\Program\\\file" and the escape character does not register in a string. How do I remove the escape character to pass it into the list as valid windows directory?

Was it helpful?

Solution

You could simplify the call if you change the current working directory for the subprocess:

from subprocess import check_call

check_call(['sox'] + self.fileselected, cwd=chosendirectory)

Note: you don't need shell=True unless you want to run an internal (shell builtin) command such as start.


Backslashes has special meaning inside Python string literals in the source code.

>>> len('\\') == 1 # a single backslash inside the string
True

Backslashes has no special meaning in a string object (in memory) i.e., you shouldn't care about backslashes unless you manually write the paths in your Python source code -- if you read the path from a file; you don't need to escape them. If you read the paths from a GUI; you don't need to escape them. If you read the paths from the output of a subprocess; you don't need to escape them, etc.

If you print repr(path); it shows you how Python string literal would look like i.e., the backslashes are doubled (escaped). If you print: [path] then it is equivalent to '['+repr(path)+']'. If you print the string along print(path) then repr is not called on the string object and the backslashes are not doubled.

For Windows paths and regex patterns, you could use raw-string literal where backslashes are not escaped e.g., r'C:\Path\n\f' == 'C:\\Path\\n\\f' (notice: r prefix).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top