Pythons read and write add \x00 to the file

2024/11/13 15:03:49

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?

Answer

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.

https://en.xdnf.cn/q/72056.html

Related Q&A

NetworkX remove attributes from a specific node

I am having a problem with networkX library in python. I build a graph that initialises some nodes, edges with attributes. I also developed a method that will dynamic add a specific attribute with a sp…

How to use Python left outer join using FOR/LIST/DICTIONARY comprehensions (not SQL)?

I have two tuples, details below:t1 = [ [aa], [ff], [er] ]t2 = [ [aa, 11,], [er, 99,] ]and I would like to get results like these below using python method similar to SQLs LEFT OUTER JOIN:res = [ [aa, …

GaussianMixture initialization using component parameters - sklearn

I want to use sklearn.mixture.GaussianMixture to store a gaussian mixture model so that I can later use it to generate samples or a value at a sample point using score_samples method. Here is an exampl…

How to use geopy vicenty distance over dataframe columns?

I have a dataframe with location column which contains lat,long location as followsdeviceid location 1102ADb75 [12.9404578177, 77.5548244743]How to get the di…

Opening a postgres connection in psycopg2 causes python to crash

Im getting the following error message when I try to open up a connection to a postgres database. Perhaps its related to OpenSSL, but I cant understand the error message. Can anyone help?>>>…

Calling generated `__init__` in custom `__init__` override on dataclass

Currently I have something like this: @dataclass(frozen=True) class MyClass:a: strb: strc: strd: Dict[str, str]...which is all well and good except dicts are mutable, so I cant use my class to key anot…

Python Watchdog process existing files on startup

I have a simple Watchdog and Queue process to monitor files in a directory. Code taken from https://camcairns.github.io/python/2017/09/06/python_watchdog_jobs_queue.htmlimport time from watchdog.events…

Updating Text In Entry (Tkinter)

The piece of code below takes input from user through a form and then returns the input as multiplied by 2. What I want to do is, when a user types a number (for example 5) and presses the "Enter&…

Python prevent overflow errors while handling large floating point numbers and integers

I am working on a python program to calculate numbers in the Fibonacci sequence. Here is my code:import math def F(n):return ((1+math.sqrt(5))**n-(1-math.sqrt(5))**n)/(2**n*math.sqrt(5)) def fib(n):for…

Python selenium sending keys into textarea

Im using Python 3.4.4 to access a website (https://readability-score.com/) that has a textarea, which dynamically updates when new values are added. Im trying to input a string into that textarea box b…