【发布时间】:2018-06-05 11:57:00
【问题描述】:
如何将带有空格、括号等的文件名解析为变量? 例如。
'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。
编辑示例代码:
>>> 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
>>>
【问题讨论】:
-
你能展示代码你是怎么做的吗?我无法复制您的问题
-
@Mangohero1 在问题中添加了代码。 :)
-
你想用这个字符串做什么?
-
@Galen 我的脚本正在下载文件,使用的类确实以初始格式保存它们。使用格式化的代码,我可以进行 shell 操作(即使用 os.system()),这仅适用于格式化的字符串
-
我建议查看
subprocess。例如:subprocess.call([r'rm', r'some name with spaces'])来自文档:“args是所有调用所必需的,并且应该是字符串或程序参数序列。通常首选提供参数序列,因为它允许模块处理任何所需的转义和引用参数(例如,允许文件名中的空格)。"
标签: python string bash shell rename