Issue
My file text.txt contains the following:
hello my
name is
jack black
and I
eat food
I'm trying to read this file into a 2D list called arr
such that arr[0][0] = hello
, arr[0][1] = my
, and so on. I'm new to Python so I don't want to use numpy yet (I see that in a lot of similar questions).
Here is part of the code I have written so far:
for x in range(5):
for y in range(2):
nextLine = my_file.readline()
nextLine = line.strip()
arr[x][y]= [nextLine.split('\t')]
print(arr[0][0])
print(arr[0][1])
However, when I print arr[0][0]
and arr[0][1]
. I get the following:
[['hello my']]
[['name is']]
What is the best way to split 'hello' and 'my' such that each one enters the 2D list correctly in the same row?
Solution
Don't use line counts. Just read until the file is empty. And .strip
returns a list; you don't need to put it inside another list.
arr = []
for line in my_file:
arr.append( nextLine.strip().split() )
print(arr[0][0])
print(arr[0][1])
Answered By - Tim Roberts Answer Checked By - Mary Flores (PHPFixing Volunteer)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.