2

我正在尝试复制文件,

>>> 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() 时,文件不会正确返回。所以它不是替代品。

4

4 回答 4

2

(在正则表达式(分组)中具有特殊含义,您必须对其进行转义:

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

或者,因为您不使用正则表达式功能进行替换:

originalFile = re.sub(r'\(','\(', originalFile)
于 2011-08-13T22:54:43.203 回答
2

正则表达式r'('被翻译为启动捕获组。这就是 Python 抱怨的原因。

如果您所做的只是替换空格和括号,那么也许string.replace就可以了?

于 2011-08-13T22:57:28.353 回答
2

或者,如果您避免调用 shell(os.system)进行复制,则无需担心转义空格和其他特殊字符,

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)
于 2011-08-13T23:14:44.233 回答
0
  1. 使用 shutil.copy 复制文件,而不是调用系统。
  2. 使用 subprocess 而不是 os.system - 它避免调用 shell,因此不需要引用。
于 2011-08-13T23:07:42.223 回答