2014-02-21 302 views
0
with open('C:\Users\ehwe\Desktop\INPUT_DS_FILE.txt') as old, open('C:\Users\ehwe\Desktop\OUTPUT_DS_FILE.txt', 'w') as new: 
     for line in old: 
      if re.search('trim\(\w+\)',line) == None: 
       new.write(line) 
      else: 
       new_line = re.sub(r"trim\((\w+)\)", r"TRIM (TRIM (CHR (09) FROM \1))", line) 
       new.write (new_line) 

這段代碼從舊文件中讀取行並將其寫入新文件。它根據模式進行了某些修改。讀取和寫入文件

問題是 - 我不能夠運行的代碼 - 編譯口口聲聲說語法錯誤:無效的語法並強調逗號在第一行。

請幫忙嗎?

P.S.

下面的代碼工作正常(萬一有人指出,斜線可能出錯)

with open('C:\Users\ehwe\Desktop\INPUT_DS_FILE.txt') as old: 
    for line in old: 
     if re.search('trim\(\w+\)',line) != None: 
      print 'Y' 
+0

您正在使用哪個版本的python? –

+0

斜槓是一個問題。解釋者有可能錯誤地指出錯誤的位置。嘗試修復slases,並查看錯誤是否更改。 – user590028

+0

Python 2.6.5,sir – Dennis

回答

0

你需要躲避反斜槓在打開的語句

with open('C:\\Users\\ehwe\\Desktop\\INPUT_DS_FILE.txt') as old, open('C:\\Users\\ehwe\\Desktop\\OUTPUT_DS_FILE.txt', 'w') as new: 
... 

需要,您可以隨時使用正斜槓,並避免反斜槓問題(fyi-windows完全理解並接受正斜槓),例如:

with open('C:/Users/ehwe/Desktop/INPUT_DS_FILE.txt') as old, open('C:/Users/ehwe/Desktop/OUTPUT_DS_FILE.txt', 'w') as new: 
... 
+2

或者只是使用正斜槓。 –

+0

斜線不是原因。請參閱對我的問題的編輯 – Dennis

+0

我正在添加此確切說明(就像您發佈的那樣) – user590028

0

或使用Python原始字符串:

with open(r'C:\Users\ehwe\Desktop\INPUT_DS_FILE.txt') as old, open(r'C:\Users\ehwe\Desktop\OUTPUT_DS_FILE.txt', 'w') as new: