0

So I want to read each character (separated by spaces) of each line of a text file and add them to a seperate index of a list for each line.

file = open("theTextFile.txt", 'r+')
pal = []

words = file.split(' ')
pal.append(words)

print(pal)
split_line(file)

The text file has a single character separated by a space for each line. The editor wouldn't allow for my punctuation from the text file, but below is an example of what it looks like.

r o t o r

r a c e c

Liam G
  • 771
  • 2
  • 9
  • 26
  • [This](http://stackoverflow.com/questions/3277503/how-do-i-read-a-file-line-by-line-into-a-list?rq=1) will be helpful. – Sangbok Lee Mar 29 '17 at 12:46
  • Can you give a short example of the input and the expected output? – AndreyF Mar 29 '17 at 12:56
  • There are so many posts here on SO on how to read a file in Python and output it into a list like [here](http://stackoverflow.com/questions/28781476/turning-list-from-text-file-into-python-list), [here](http://stackoverflow.com/questions/35273534/python-read-lines-of-an-entire-file-and-efficiently-storing-the-ones-i-want-in) or [here](http://stackoverflow.com/questions/37002578/python-read-file-into-list-edit) you should be able to figure this one out. But your question is not clear, you need to give an example of "theTextFile.txt" and tell us what your expected output is. – dirkgroten Mar 29 '17 at 13:07

2 Answers2

0

Maybe you want like this?

words = []
with open('theTextFile.txt', 'r') as fp:
    words = sum([l.strip().split(' ') for l in fp], [])
print(words)
tell k
  • 605
  • 2
  • 7
  • 18
0

This is what I did to solve my issue:

lines = open('theTextFile.txt','r')

secondList = []
for line in lines:
    line = line.split()
    secondList.append(line)
Liam G
  • 771
  • 2
  • 9
  • 26