Đang chuẩn bị nút TẢI XUỐNG, xin hãy chờ
Tải xuống
Tham khảo tài liệu 'programming in python 3 - part 6', công nghệ thông tin, kỹ thuật lập trình phục vụ nhu cầu học tập, nghiên cứu và làm việc hiệu quả | 298 Chapter 7. File Handling en.wikipedia.org the format will be H16s little-endian byte order 2-byte unsigned integer 16-byte byte string and the bytes object that is returned will be b x10 x00en.wikipedia.org . Conveniently Python shows bytes objects in a compact form using printable ASCII characters where possible and hexadecimal escapes and some special escapes like t and n otherwise. The pack_string function can handle strings of up to 65535 UTF-8 characters. We could easily switch to using a different kind of integer for the byte count for example a 4-byte signed integer format i would allow for strings of up to 231-1 more than 2 billion characters. The struct module does provide a similar built-in format p that stores a single byte as a character count followed by up to 255 characters. For packing the code using p format is slightly simpler than doing all the work ourselves. But p format restricts us to a maximum of 255 UTF-8 characters and provides almost no benefit when unpacking. For the sake of comparison versions of pack_string and unpack_string that use p format are included in the convert-incidents.py source file. We can now turn our attention to the rest of the code in the export_binary method. fh None try if compress fh gzip.open filename wb else fh open filename wb fh.write MAGIC fh.write FORMAT_VERSION for incident in self.values data bytearray data.extend pack_string incident.report_id data.extend pack_string incident.airport data.extend pack_string incident.aircraft_id data.extend pack_string incident.aircraft_type data.extend pack_string incident.narrative.strip data.extend NumbersStruct.pack incident.date.toordinal incident.pilot_percent_hours_on_type incident.pilot_total_hours incident.midair fh.write data return True Writing and Reading Binary Data 299 Table 7.1 Bytes and Bytearray Methods 1 Syntax Description ba.append i Appends int i in range 0.255 to bytearray ba Character encodings 91 b.capitalize b.center width byte b.count x start end