I see two problems.
1: Your file
class isn't inheriting from any specific class. If I've interpreted the situation correctly, it should be a subclass of io.TextIOWrapper
.
2: In both Python 2.6 and 3.x, the types
module (which would need to be imported in the first place) has no element bytes
. The recommended method is to just use bytes
on its own.
Redone snippet:
import io, sys
class file(io.TextIOWrapper):
def write(self, d, encoding=sys.getdefaultencoding()):
if isinstance(d, bytes):
d = d.decode(encoding)
super().write(d)
old_stdout = sys.stdout # In case you want to switch back to it again
sys.stdout = file(open(output_file_path, 'w').detach()) # You could also use 'a', 'a+', 'w+', 'r+', etc.
Now it should do what you want it to, using sys.stdout.write
to the output file that you specify. (If you don't wish to write to a file on disk but instead wish to write to the default sys.stdout
buffer, using sys.stdout = file(sys.stdout.detach())
would probably work.)
Do note that, since Python 3.x does not have the file
class, but 2.6 does have the io
module, you will have to use one of the classes of the io
module. My above code is just an example, and if you want it to be more flexible you'll have to work that out on your own. That is, depending on what sort of file you're writing to/what mode you're writing to in, you'll probably want to use a different class in io
.