A space adds in the file everytime we run the code in python


I’m trying to add some data to file in the form of a list.the problem is that every time I run the code a space is added in the list items.for example the list is empty and added "hello" to the list.

The list will look like this:


So as you can see the first list item is an empty list item(index:0). After the empty list item my "hello" is added.

Now if I run the code again and add "world" to it.

The list will look this:

['',' hello','world']

So you can see there is space before "hello" but "world" is proper

And again if I run the code and add "helloworld" It will look like this:

['',' hello',' world','helloworld']

So now one more space is there is hello and one in world.

So if someone could help I would be really thank full:)

directory = "F"

with open(f"{directory}:\\My_codes\\python\\question_data.txt","r") as rbb:
    readb = rbb.read()
with open(f"{directory}:\\My_codes\\python\\question_data.txt","w") as qw:
    var1 = readb.replace("[",'')
    var1_2 = var1.replace("'","")
    var2 = var1_2.replace("]",'')
    var3 = var2.replace('"','')
    readbl = var3.split(',')
    readbl.append(input("Type the question here:"))
    question_data = readbl


>Solution :

The line:

readbl = var3.split(',')

is the problem since, when var3 is empty, the split() method adds an empty string.

Its easy to fix like this:

readbl = var3.split(',') if var3 else []

Also, you should consider using json to store strings in a list, rather than doing your own parsing:

import json
import os    

directory = "F"
fullpath = f"{directory}:\\My_codes\\python\\question_data.txt"

readbl = []
if os.path.getsize(fullpath) > 0:
    with open(fullpath,"r") as rbb:
        readbl = json.load(rbb)

readbl.append(input("Type the question here:"))

with open(fullpath,"w") as qw:
    json.dump(readbl, qw)


Leave a ReplyCancel reply