Home > OS >  How to split (and store) data from text file?
How to split (and store) data from text file?

Time:10-28

I have a text file that isformatted where there is data that is being separated with ; (for example apples;oranges;grapes), and I need to split the list into 3 separate items (apples, oranges, grapes). So far my code is as follows

doc = open("doc.txt", "r")
alist = []
line = doc.readline()
line = line.strip()
stuff = line.split(";")
alist.append(stuff)
print(alist)
print(len(alist))

But the output is just all the items in the list stores as one element ["Apples", "Oranges", "Grapes] with the len() of 1

I would need them to be separated so that I could use formatting when printing

Thanks for the help! :)

CodePudding user response:

its because you are using append which inserts whole list at the rear end of list instead use extend as below example might be useful to differentiate both:

>>> a = []
>>> a.extend([1,2,3])
>>> a
[1, 2, 3]
>>> a.append([4,5,6])
>>> a
[1, 2, 3, [4, 5, 6]]
>>> 

CodePudding user response:

You can use a for loop to append each item one by one.

for i in stuff:
    alist.append(i)
  • Related