我有一个包含递归目录列表输出的文本文件,通常如下所示:
./subfolder/something with spaces:
something\ with\ spaces.txt*
something\ with\ spaces.dat*
./subfolder/yet another thing:
yet\ another\ thing.txt*
yet\ another\ thing.dat*
我需要获取每个 .txt 文件的完整路径列表:
./subfolder/something with spaces/something with spaces.txt
./subfolder/yet another thing/yet another thing.txt
我几乎找到了解决方案,但是在 Python 中取消转义文件名的最佳解决方案是什么?我不确切知道哪些字符 ls -R
转义了(不过空格和 = 是两个这样的字符)。我也无权访问包含这些文件的驱动器,因此不幸的是,使用更好的命令来获取列表是不可能的。
最佳答案
我不确定是否有内置的,但可以使用一个简单的正则表达式。
re.sub(r'(?<!\\)\\', '', filename)
这将删除所有反斜杠(除了那些跟在另一个反斜杠之后的反斜杠)。这似乎是您尝试在终端上 echo
这些值时的行为(我只在 bash 中测试过)。
bash-3.2$ echo foo\\bar
foo\bar
bash-3.2$ echo foo\ bar
foo bar
bash-3.2$ echo foo\=bar
foo=bar
这是一个完整的 python 示例:
import re
def unescape(filename):
return re.sub(r'(?<!\\)\\', '', filename)
print unescape(r'foo\ bar')
print unescape(r'foo\=bar')
print unescape(r'foo\\bar')
输出:
foo bar
foo=bar
foo\bar
关于python - 转义 ls -R 生成的文件名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8690640/