读写文件

时间:2014-02-21 11:09:46

标签: python regex file

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)

这段代码从旧文件中读取行并将其写入新文件。它根据模式进行某些修改。

问题是 - 我无法运行代码 - 编译器一直在说 SyntaxError:无效语法,并在第一行突出显示逗号

请帮忙吗?

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'

2 个答案:

答案 0 :(得分: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:
...

答案 1 :(得分:0)

或者使用Python Raw字符串:

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: