Python's read and write add \x00 to the file

泪湿孤枕 提交于 2021-01-26 14:46:23

问题


I have come across a weird problem when working with files in python. Let's say I have a text file and a simple piece of code that reads the contents of the file and then rewrites it with unaltered contents.

File.txt

This is a test file

Python code

f=open(File.txt,'r+')
data=f.read()
f.truncate(0)
f.write(data)
f.close()

After running the above code File.txt seems to be the same. However, when I opened it in a hex editor I was surprised to see lots of \x00 (NULL) bytes before the actual contents of the text file, that wasn't there before.

Can anyone please explain?


回答1:


Suppose your file has 20 bytes in it. So f.read() reads 20 bytes. Now you truncate the file to 0 bytes. But your position-in-file pointer is still at 20. Why wouldn't it be? You haven't moved it. So when you write, you begin writing at the 21st byte. Your OS fills in the 20 missing bytes with zeroes.

To avoid this, f.seek(0) before writing again.




回答2:


f.truncate(0) sets all bytes of the file to \x00. However, it does not change the file pointer - you're still at the position after the call to read. Therefore, if you write anything, the operating system will extend the file to the new length (the original length + len(data)).

To avoid that, call seek:

with open('File.txt', 'r+') as f:
  data=f.read()
  f.seek(0)
  f.truncate(0)
  f.write(data)


来源:https://stackoverflow.com/questions/9729452/pythons-read-and-write-add-x00-to-the-file

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!