Python Syntactical error could be the indent? -


when trying run script getting error:

valueerror: i/o operation on closed file.

i checked similar questions , doc, yet no success. , while error clear enough haven't been able figure out. apparently missing something.

# -*- coding: utf-8 -*- import os import re  dirpath = 'path\\to\\dir' filenames = os.listdir(dirpath) nb = 0  open('path\\to\\dir\\file.txt', 'w') outfile:     fname in filenames:         nb = nb+1         print fname         print nb         currentfile = os.path.join(dirpath, fname)  open(currentfile) infile:     line in infile:         outfile.write(line) 

edit: since removed with open message error changed to:

`open (c:\\path\\to\\\\file.txt, 'w') outfile` : 

syntaxerror : invalid syntax pointer underneath as

edit: confusion question. after all, restored with , fixed indents bit. , working fine!

it looks outfile @ same level infile - means @ end of first with block, outfile closed, can't written to. indent infile block inside infile block.

with open('output', 'w') outfile:     in b:         open('input') infile:         ...     ... 

you can simplify code here using fileinput module, , making code clearer , less prone wrong results:

import fileinput contextlib import closing import os  closing(fileinput.input(os.listdir(dirpath))) fin, open('output', 'w') fout:     fout.writelines(fin) 

Comments