Python / Bash-获取带有转义字符的文件名


'Album Artist - Song name (feat Musician) [Year]'

'Album\ Artist\ \- Song\ name\ \(feat\ Musician\)\ \[Year\]'

我用re.escape(filename)得到正确的格式.但是,如果我将打印内容从re.escape存储到变量中,则它会反转为初始命名.我知道我可以使用“ string” .replace(‘x’,’y’)方法.但这对我来说并不安全.

使用Python 3.5.3 btw.


>>> import re 
>>> # this is an example array in the format how my filenames are named stored in files                                                                  >>> files = ['AA - BB (CC) [DD]', 'EE - FF (GG) [HH]', 'II - JJ (KK) [LL]']
>>> for f in files:
...     print(f)
AA - BB (CC) [DD]
EE - FF (GG) [HH]
II - JJ (KK) [LL]
>>> for f in files:
...     print(re.escape(f))
AA\ \-\ BB\ \(CC\)\ \[DD\] # desired format
EE\ \-\ FF\ \(GG\)\ \[HH\]
II\ \-\ JJ\ \(KK\)\ \[LL\]
>>> escaped = re.escape(files[0])
>>> escaped
'AA\\ \\-\\ BB\\ \\(CC\\)\\ \\[DD\\]' # actual result



具体来说,请参见frequently used arguments

args is required for all calls and should be a string, or a sequence of program arguments. Providing a sequence of arguments is generally preferred, as it allows the module to take care of any required escaping and quoting of arguments (e.g. to permit spaces in file names). If passing a single string, either shell must be True (see below) or else the string must simply name the program to be executed without specifying any arguments.


import subprocess

file_names = [r'AA - BB (CC) [DD]', r'EE - FF (GG) [HH]', r'II - JJ (KK) [LL]']

for file_name in file_names:[r'touch', file_name])