开发者

Substitute parenthesis for their regular expression

I'm trying to copy a file,

>>> 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)

But must first replace the spaces and parenthesis before the open function will work:

/Users/alvinspivey/Documents/workspace/Image_PCA/spectra_text/HIS/jean\ paul\ test\ 1\ -\ Copy\ \(2\)/bean-1-aa.txt

spaces ' ' --> '\ ' parenthesis '(' --> '\(' etc.

Replacing the spaces work:

>>> originalFile = re.sub(r'\s',r'\ ', os.path.join(root,file))

but parenthesis return an error:

>>> originalFile = re.sub(r'(',r'\(', originalFile)

Traceback (most recent call last): File "", line 1, in File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/re.py", line 151, in 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 expression sre_constants.error: unbalanced parenthesis

Am I replacing parenthesis correctly?

Also, when using re.escape() for this, the file is not returned correctly. So it is not an alternative.


( has special meaning in regular expressions (grouping), you have to escape it:

originalFile = re.sub(r'\(',r'\(', originalFile)

or, since you don't use regex features for the replacement:

originalFile = re.sub(r'\(','\(', originalFile)


The regular expression r'(' is translated as start a capturing group. Which is why Python is complaining.

If all you are doing is replacing spaces and parenthesis then maybe just string.replace will do ?


Alternatively, if you avoid calling a shell (os.system) to do the copy, you don't need to worry about escaping spaces and other special characters,

import shutil

originalFile = '/Users/alvinspivey/Documents/workspace/Image_PCA/spectra_text/HIS/jean paul test 1 - Copy (2)/bean-1-aa.txt'
newTmpFile = '/whatever.txt'
shutil.copy(originalFile, newTmpFile)


  1. Use shutil.copy to copy files, rather than calling the system.
  2. Use subprocess rather than os.system - it avoids calling into the shell, so doesn't need the quoting.
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜