【发布时间】:2011-10-26 14:18:06
【问题描述】:
我正在尝试复制文件,
>>> 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)
Traceback(最近一次调用最后一次): 文件“”,第 1 行,在 文件“/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/re.py”,第 151 行,在子 return _compile(pattern, flags).sub(repl, string, count) _compile 中的文件“/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/re.py”,第 244 行 raise error, v # 无效表达式 sre_constants.error:括号不平衡
我是否正确替换了括号?
此外,当为此使用 re.escape() 时,文件不会正确返回。所以它不是替代品。
【问题讨论】:
-
您可以使用shutil.copy(copy2,或copyfile)代替系统cp命令,从而避免一开始就需要转义路径。
标签: python regex parentheses