val*_*s21 6 python string bash shell rename
如何将带有空格、括号等的文件名解析为变量?前任。
'Album Artist - Song name (feat Musician) [Year]'
Run Code Online (Sandbox Code Playgroud)
到
'Album\ Artist\ \- Song\ name\ \(feat\ Musician\)\ \[Year\]'
Run Code Online (Sandbox Code Playgroud)
我得到了正确的格式re.escape(filename)。但是,如果我将打印内容存储re.escape到一个变量中,它会反转为初始命名。我知道我可以使用这个"string".replace('x', 'y')方法。但它对我来说并不安全。
有谁知道我如何解决这个问题或解决这个问题?顺便说一句,使用 Python 3.5.3。
编辑示例代码:
>>> 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
>>>
Run Code Online (Sandbox Code Playgroud)
根本问题听起来像是传递可能包含需要转义为另一个程序的参数的字符的文件名。我建议看看subprocess。
具体来说,请参阅常用参数:
args所有调用都需要它,并且应该是一个字符串或程序参数序列。通常优选提供参数序列,因为它允许模块处理任何所需的参数转义和引用(例如,允许文件名中存在空格)。如果传递单个字符串,则 shell 必须为 True(见下文),否则该字符串必须简单地命名要执行的程序而不指定任何参数。
例如:
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:
subprocess.call([r'touch', file_name])
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1976 次 |
| 最近记录: |