python - Is it safe to add or remove null bytes at the end of a file? -


is always safe remove trailing 0 or null bytes end of file? i'm worried might corrupt file uses utf-16 encoding, or other reason.

and further, always safe add trailing 0 bytes end of file?

as example using python i'd stripping single bytes file's end until 0 bytes removed:

with open('in.ext', 'rb') file_in:     open('out.ext', 'wb') file_out:         data = file_in.read()         while data.endswith('\x00'):             data = data[:-1]         file_out.write(data) 

this purpose of storing , retrieving arbitrary files on portable storage medium. hoping away padding half written byte blocks (a block contains 16 bytes) 0 bytes , stripping bytes off when reading data back.

it depends on application writing , reading files. unless know exact format of file, no modification safe default. if know format, obvious if trailing 0s needed or not.

after question edit: "storing , retrieving arbitrary files" default incompatible randomly stripping bytes. doesn't matter bytes are, need preserve files were. if need proper padding scheme, have @ stuff used in encryption algorithms - example pkcs7.