myArray = []
textFile = open("file.txt")
lines = textFile.readlines()
for line in lines:
myArray.append(line.split(" "))
print (myArray)
This code outputs
[['a\n'], ['b\n'], ['c\n'], ['d']]
What would I need to do to make it output
a, b, c, d
You're adding a list
to your result (split
returns a list). Moreover, specifying "space" for split character isn't the best choice, because it doesn't remove linefeed, carriage return, double spaces which create an empty element.
You could do this using a list comprehension, splitting the items without argument (so the \n
naturally goes away)
with open("file.txt") as lines:
myArray = [x for line in lines for x in line.split()]
(note the with
block so file is closed as soon as exited, and the double loop to "flatten" the list of lists into a single list: can handle more than 1 element in a line)
then, either you print the representation of the array
print (myArray)
to get:
['a', 'b', 'c', 'd']
or you generate a joined string using comma+space
print(", ".join(myArray))
result:
a, b, c, d
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With