PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Wednesday, November 2, 2022

[FIXED] How do I split a line from a file into a 2D list?

 November 02, 2022     arrays, file, list, python, split     No comments   

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)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing