gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 14:48:00 26 4
gpt4 key购买 nike

如何将带有空格、括号等的文件名解析为变量?例如。

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

最佳答案

潜在的问题听起来像是将可能包含需要作为参数转义的字符的文件名传递给另一个程序。我建议看看 subprocess .

具体参见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:
subprocess.call([r'touch', file_name])

关于Python/Bash - 获取带有转义字符的文件名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47948120/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com