我正在尝试编写一个python工具,它将读取日志文件并对其进行处理
它应该做的一件事是使用日志文件中列出的路径(它是备份工具的日志文件)
/Volumes/Live_Jobs/Live_Jobs/*SCANS\ and\ LE\ Docs/_LE_PROOFS_DOCS/JEM_lj/JEM/0002_OXO_CorkScrew/3\ Delivery/GG_Double\ Lever\ Waiters\ Corkscrew_072613_Mike_RETOUCHED/gg_3110200_2_V3_Final.tif
Run Code Online (Sandbox Code Playgroud)
不幸的是,我提供的路径没有被适当地转义,我在python中正确地逃脱了.也许python不是最好的工具,但我喜欢它的灵活性 - 它可以让我扩展我写的任何东西
使用正则表达式转义函数转义太多字符,pipes.quote方法不会逃避空格,如果我使用正则表达式替换''与'\'我最终得到
/Volumes/Live_Jobs/Live_Jobs/*SCANS\\ and\\ LE\\ Docs/_LE_PROOFS_DOCS/JEM_lj/JEM/0002_OXO_CorkScrew/3\\ Delivery/GG_Double\\ Lever\\ Waiters\\ Corkscrew_072613_Mike_RETOUCHED/gg_3110200_2_V3_Final.tif
Run Code Online (Sandbox Code Playgroud)
这是双重转义,不会传递给像python这样的函数os.path.getsize().
我究竟做错了什么??
如果您正在读取文件中的路径,并将它们传递给类似的函数os.path.getsize,则无需转义它们.例如:
>>> with open('name with spaces', 'w') as f:
... f.write('abc\n')
>>> os.path.getsize('name with spaces')
4
Run Code Online (Sandbox Code Playgroud)
事实上,只有一个在Python需要空间逃脱的功能一把,要么是因为他们传递一个字符串到外壳(像os.system),或者是因为他们正在试图做代表你的壳状解析(如subprocess.foo用arg字符串而不是arg列表).
所以,让我们说logfile.txt看起来像这样:
/Volumes/My Drive/My Scans/Batch 1/foo bar.tif
/Volumes/My Drive/My Scans/Batch 1/spam eggs.tif
/Volumes/My Drive/My Scans/Batch 2/another long name.tif
Run Code Online (Sandbox Code Playgroud)
...然后这样的事情会很好:
with open('logfile.txt') as logf:
for line in logf:
with open(line.rstrip()) as f:
do_something_with_tiff_file(f)
Run Code Online (Sandbox Code Playgroud)
注意到*你的例子中的那些字符,如果这些是glob模式,那也没关系:
with open('logfile.txt') as logf:
for line in logf:
for path in glob.glob(line.rstrip()):
with open(path) as f:
do_something_with_tiff_file(f)
Run Code Online (Sandbox Code Playgroud)
如果您的问题与您描述的完全相反,并且文件中包含了被转义的字符串,并且您想要decode('string_escape')取消它们,则会撤消Python样式的转义,并且有不同的函数可以撤消不同类型的转义,但是不知道你要撤消什么样的逃避,很难说你想要哪种功能......
尝试这个:
myfile = open(r'c:\tmp\junkpythonfile','w')
Run Code Online (Sandbox Code Playgroud)
“r”代表原始字符串。
你也可以使用 \ 像
myfile = open('c:\\tmp\\junkpythonfile','w')
Run Code Online (Sandbox Code Playgroud)