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)

This chunk of code reads line from old file and writes it to a new one. It makes certain modifications according to a pattern.

Problem is - I am not able to run the code - the compiler keeps saying SyntaxError: invalid syntax and highlights the comma in the very first line.

Little help please?

P.S.

the code below works fine (in case someone points out that slashes might go wrong)

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'
Denys
  • 4,287
  • 8
  • 50
  • 80

2 Answers2

0

You need to escape the backslashes in your open statement

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

Optionally, you can always use forward slashes, and avoid the backslash issue (fyi -- windows fully understands and accepts forward slashes), eg:

with open('C:/Users/ehwe/Desktop/INPUT_DS_FILE.txt') as old, open('C:/Users/ehwe/Desktop/OUTPUT_DS_FILE.txt', 'w') as new:
...
user590028
  • 11,364
  • 3
  • 40
  • 57
0

Or use Python Raw strings:

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:
sateesh
  • 27,947
  • 7
  • 36
  • 45