我有一个文本文件,其中包含递归目录列表的输出,通常如下所示:
./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
转义(空格和=是两个这样的字符)。我也无法访问包含这些文件的驱动器,因此不幸的是,使用更好的命令获取列表是不可能的。
答案 0 :(得分:1)
我不确定是否有内置功能,但可以使用简单的正则表达式。
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