-1

What I want to do: I have a list now and want to add it to the bottom of the existing text file. However, when the new line is added, the commas doesn't appear

What I have done so far: Current txt file:

food,bought
oranges,yes
strawberry,no

my code

choice=input("What fruit?")
item=[]
item.append(choice)
item.append("No")

with open('groceries.txt', 'a+') as file:
    file.writelines(item)

result of my code

food,bought
oranges,yes
strawberry,no
applesno

I want it to appear like this:

food,bought
oranges,yes
strawberry,no
apples,no

I tried to add the comma eg. item.append(choice+",") but it will change the result when i use index later on Any way to solve this?

ellle
  • 5
  • 3

1 Answers1

0

How to join a list using ,?

','.join(item)

This will give you:

apples,no

You can use it simply as:

file.writelines(",".join(item))
Harshal Parekh
  • 5,918
  • 4
  • 21
  • 43