Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

['','hello']

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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:"))
    qw.write(str(readbl))
    question_data = readbl

print(question_data)

>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)

print(readbl)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading