Python problem reading non-text format files for modification

Source: Internet
Author: User

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.