简体   繁体   中英

written out bytes size and actually size are different using python's file.write()

here is my code , it's really simple, I download a file(with lib requests ) and save it to disk,but the size i got is different from actually size write to disk

mus_resp =r.get("http://audio.xmcdn.com/group7/M07/21/73/wKgDWlbmOa3TD0D_AArDQp_Mj5Y641.m4a",headers=headers, stream=True)

#print len(mus_resp.content) here is 705346 bytes
fd = open( "file", 'w') 
fd.write(mus_resp.content)
fd.flush()
fd.close()
exit()
print os.path.getsize('file')  here is 708677 bytes

Your data is binary data, not text, and it likely contains \\n characters semi-randomly (they don't mean newlines, it's just the same byte as ASCII newline). When you write them to a text mode file on Windows, it's seamlessly converting to \\r\\n (Windows standard line endings), bloating the final file. Open the file in binary mode and you'll disable line ending conversions:

fd = open("file", 'wb')  # 'wb' means write binary mode

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