M. Saeb
M. Saeb

Reputation: 79

Empty spaces are being automaticlly added when I write a text file in python

I'm trying to use json library to edit a text file on my PC, the this is what the Text.txt file contains:

{"name": "mike", "born": 1998}

and this is the code that I'm writing

import json

text = """\
{
"look": "avarage",
"income": "high"
}"""
File = open("Test.txt", "r+")
json_from_file = json.load(File)
json_from_text = json.loads(text)
json_from_file.update(json_from_text)
File.truncate(0)
json.dump(json_from_file, File)
File.close()

the Text.txt should contain:

{"name": "mike", "born": 1998, "look": "avarage", "income": "high"}

but instead I get several empty spaces at the beginning (31 in total) that it looks like this

                              {"name": "mike", "born": 1998, "look": "avarage", "income": "high"}

any idea how I can get rid off it ?

Upvotes: 0

Views: 116

Answers (1)

Spaceghost
Spaceghost

Reputation: 6985

Replace truncate with seek:

import json

text = """\
{
"look": "avarage",
"income": "high"
}"""
File = open("Test.txt", "r+")
json_from_file = json.load(File)
json_from_text = json.loads(text)
json_from_file.update(json_from_text)
File.seek(0)
json.dump(json_from_file, File)
File.close()

File.truncate doesn't change the current file position, and since you've already read the file you are at the of it (31 characters in your example).

Keep in mind that if you were the modify the file in a way that would make it shorter, File.seek alone will not do, as you might leave undesired characters at the end.

Upvotes: 1

Related Questions