Monday, 15 June 2015

python - writing file & displaying result in idle -



python - writing file & displaying result in idle -

trying process text file , see output in idle redirected text file. due text formatting, need maintain statement in print function (end = ''). looking way utilize "end = ''" , "file=output_file" simultaneously print function.

import re input_file = open ('e:\input.txt','r') output_file = open ('e:\output.txt','w') line in input_file: if re.match('ab|cd', line): print ('line ab or cd: ', end = '',file=output_file ) print (line, end = '',file=output_file) print (' --------', file=output_file) print (' --------',file=output_file) print ('!',file=output_file) else: print (line,file=output_file)

to write several places using single print(), define file-like object:

class="lang-py prettyprint-override">class teefile(object): def __init__(self, *files): self.files = files def write(self, data): f in self.files: f.write(data) def flush(self): f in self.files: f.flush()

example:

class="lang-py prettyprint-override">import sys file = teefile(sys.stderr, output_file) print("abc", end="", file=file) file.flush()

python python-3.x

No comments:

Post a Comment