A question not published (I solve it if I write) in 2017.3.20
I just wanted to publish it-stackoverflow, but I solved it.
1.Platform:windows 8
I ' m just trying to modify a file in Python 2.7, which are not in plain text
(like. txt,. csv) but docx format,in order to add one or more bytes to
It.
However, when I tried to read it through commands:
With open (' Ggg.docx ', ' rb+ ') as F:
Contents = F.read () # Type (contents): str
With open (' Ggg2.docx ', ' rb+ ') as F:
F.writelines (contents)
, the result is appears to being write str to ggg2.docx, instead of bytes
Format of Ggg.docx:
504B 0304 1400 0600 0800 0000 2100 C1F0
070c 7801 0000 5a06 0000 1300 0802 5B43
6f6e 7465 6e74 5f54 7970 6573 5d2e 786d
6c20 a204 0228 a000 0200 0000 0000 0000
0000 0000 0000 0000 0000 0000 0000 0000
...
Format of Ggg2.docx:
504b 0304 1400 0600 0800 0000 2100 C1f0
070c 7801 0000 5a06 0000 1300 0802 5B43
6f6e 7465 6e74 5f54 7970 6573 5d2e 786d
6c20 a204 0228 a000 0200 0000 0000 0000
0000 0000 0000 0000 0000 0000 0000 0000
They look the same in editor (Sublime), but ggg2.docx are in fact
The plain text ' 504B 0304 ... '
2. The 2:
A similar question is ' http://stackoverflow.com/questions/21677646/ Python-writing-a-two-byte-string-as-a-single-byte-hex-character-to-a-binary-fi
' But it's doesn ' t work.
3. The 3:
In Http://stackoverflow.com/questions/12092527/python-write-bytes-to-file,
A method is proposed like this:
Import IO
With open (' Ggg.docx ', ' rb+ ') as F:
Contents = F.read () # Type (contents): str
With Io.open (' Ggg2.docx ', ' rb+ ') as F:
F.writelines (contents)
But the link the user suggests it (open instead of io.open) is useful in Windows.
Now it works .....
Thank all the guys.
YEP, I just want to give complaints to the designer of Python that made this.
Python problem reading non-text format files for modification