How do I override file.write() in Python 3? -
The code below works on Python 2.6 but not on Python 3.x:
old_file_write = File.write class file (): def write (self, d): if isinstance (d, types.bytes): self.buffer.write (d) Other: old_file_write (d) # ... something I can not change the code or f = open ("x") f.write ("...") f.write (b "...") sys.stdout.write (b "...") system Do not want to. Stdout.write ("...") print (b "...") print ("...")
The problem is that the first line one in Python 3.x Error will occur:
name error: name 'file' is not defined
How can I do this in Python 3.x?
In fact, two years later, I am still looking for a solution that will work on both versions (2.5+, and 3.x).
For those, who are still wondering why I am looking for it, only to work with new versions of Python old code (other code, which sometimes you have not modified Can be able to create).
This is not about my code, that is how you can write some code that plays well with bad code):
I see two problems.
1: Your file
class is not hereditary to any particular class. If I have interpreted the situation properly, then it should be a subclass of io.TextIowrapper
.
2: In both Python 2.6 and 3.x, there is no element in type
module (which will need to be imported in the first place) byte
. Recommended method is to use only byte
on your code.
Radon snippet:
Import io, sys class file (io.TextIowrapper): Def Def (self, d, encoding = sys.getdefaultencoding ()): if isinstance (D, bytes): d = d.decode (encoding) super (). Type (D) old_stdout = sys.stdout # If you can also use it 'a', 'a +', 'w +', 'r +', etc. / Code> Now it should use the sys.stdout.write
in the output file you specify. (If you do not want to write to a disk on a disk, but instead want to type the default sys.stdout
buffer, then sys.stdout = file (sys.stdout.detach)) < / Code> will probably work.)
Note that, because Python 3.x does not have a file
class, but 2.6 has IO
module , You 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, then you have to work on it. That is, what type of file you are writing / what mode you are writing in, you probably want to use a different class in io
.
Comments
Post a Comment