简体   繁体   中英

How to write integers with different sizes to a file

in my code, I write integers and string to the same line of an output text file as follows:

f.write("%d\t%d\t%d\t%s"%(int_2b_var, int_4b_var, int_8b_var, string_val))

where int_2b_val needs to be an integer of 2 bytes, int_4b_var an int of 4 bytes and int_8b_var an int of 8 bytes.

How can I manage to write the int variables with the desired length into my txt file?

  1. you need to write bytes (and open the file in binary mode) as here you're going to write a textual representation of the numbers and eg the textual representation of 1 byte is up to 4 characters (-128)
  2. use the struct module, which is used to pack data into binary form, see the format characters for how to specify the details of your packing eg byte order
  3. you'll also need to encode string_val and decide how you want to reify it exactly eg s needs a hard-coded number of items (so you might need to encode the string length as well), p is limited to 255 bytes, ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM