Python File I/O: invalid syntax?
我试图打开两个文件,其中一个包含内容,另一个为空。对于不是头的行,我读取每一行并在将处理过的行写入空文件之前对其进行处理,直到到达第一个文件的结尾。
我在第二行收到一个"无效语法错误"(打开…),不知道原因。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | 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 + ' ') count += 1 except IOError as e: print 'Operation failed: %s' % e.strerror |
尝试嵌套它们,如果有其他错误,则会更明显:
1 2 3 | with open(file_read, 'r') as file_r: with open(file_write, 'w') as file_w: [CODE HERE] |
如果运行的版本早于2.7,则可以将