我正在尝试复制文件,
>>> originalFile = '/Users/alvinspivey/Documents/workspace/Image_PCA/spectra_text/HIS/jean paul test 1 - Copy (2)/bean-1-aa.txt'
>>> copyFile = os.system('cp '+originalFile+' '+NewTmpFile)
但必须先替换空格和括号,然后才能使用 open 函数:
/Users/alvinspivey/Documents/workspace/Image_PCA/spectra_text/HIS/jean\ paul\ test\ 1\ -\ Copy\ \(2\)/bean-1-aa.txt
空格 ' ' --> '\' 括号 '(' --> '\(' 等。
替换空间工作:
>>> originalFile = re.sub(r'\s',r'\ ', os.path.join(root,file))
但括号返回错误:
>>> originalFile = re.sub(r'(',r'\(', originalFile)
回溯(最后一次调用):文件“”,第 1 行,在文件“/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/re.py”中,第 151 行,在 sub return _compile( pattern, flags).sub(repl, string, count) File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/re.py", line 244, in _compile raise error, v # invalid表达式 sre_constants.error:不平衡括号
我是否正确替换了括号?
此外,当为此使用 re.escape() 时,文件不会正确返回。所以它不是替代品。