1

I'm trying to open 2 files, one of which has content and one which is empty. For the lines that are not headers, I read each line and process it before writing the processed line to the empty file, until the end of the first file is reached.

I'm getting an 'Invalid syntax error on the 2nd line (with open...), and have no idea why.

try:
    with open(file_read, 'r') as file_r, open(file_write, 'w') as file_w:
        for line in file_r:
            while line != '':
                if count > 10:
                    line = line.split()
                    colour_int = int(line[-1]) # colour is stored as the last (4th) value in each line
                    red = (colour_int >> 16) & 255
                    green = (colour_int >> 8) & 255
                    blue = colour_int & 255
                    new_line = str.join([ line[0], line[1], line[2], red, green, blue ])
                    file_w.write(new_line + '\n')
                    count += 1
except IOError as e:
    print 'Operation failed: %s' % e.strerror
chepner
  • 497,756
  • 71
  • 530
  • 681
bard
  • 2,762
  • 9
  • 35
  • 49
  • What version of Python? 2.7? – rdodev Nov 27 '13 at 20:18
  • did you try the solution below? – rdodev Nov 27 '13 at 20:25
  • Yep, it worked! I'm not sure why putting them on one line didn't though, as in this thread: http://stackoverflow.com/questions/4617034/python-open-multiple-files-using-with-open – bard Nov 27 '13 at 20:33
  • it might depend on the specific version of python you have in your system (not just v2.6 to 2.7), but sometime vendors will bundle versions of Python that have been tweaked from original distribution. – rdodev Nov 27 '13 at 20:35
  • I see, thanks for your help! Appreciate it. – bard Nov 27 '13 at 20:49

1 Answers1

1

Try nesting them and if there's another error it shold be more obvious:

with open(file_read, 'r') as file_r:
    with open(file_write, 'w') as file_w:
     [CODE HERE]

If you are running a version older than 2.7, you can add from __future__ import with_statement to the top of the file to get the forward-port.

rdodev
  • 3,164
  • 3
  • 26
  • 34