Reading a file into a multidimensional array using Python

If I have a text file:

Hello World How are you? Bye World 

How would I read it in a multidimensional array like this:

 [["Hello", "World"], ["How", "are", "you?"], ["Bye" "World"]] 

I tried:

 textFile = open("textFile.txt") lines = textFile.readlines() for line in lines: line = lines.split(" ") 

But it just returns:

 ["Hello World\n", "How are you?\n", "Bye World"] 

How to read a file in a multidimensional array?

+6
source share
4 answers

Use list comprehension and str.split :

 with open("textFile.txt") as textFile: lines = [line.split() for line in textFile] 

Demo:

 >>> with open("textFile.txt") as textFile: lines = [line.split() for line in textFile] ... >>> lines [['Hello', 'World'], ['How', 'are', 'you?'], ['Bye', 'World']] 

with statement :

It is good practice to use the with keyword when working with file objects. This has the advantage that the file closes correctly after its set ends, even if an exception occurs in the path. it is also much shorter than writing equivalent try-finally blocks.

+10
source

You can use map with the unrelated str.split method:

 >>> map(str.split, open('testFile.txt')) [['Hello', 'World'], ['How', 'are', 'you?'], ['Bye', 'World']] 

In Python 3.x, you need to use list(map(str.split, ...)) to get the list, because map in Python 3.x returns an iterator instead of a list.

+3
source

Also remember to use strip to remove \n :

 myArray = [] textFile = open("textFile.txt") lines = textFile.readlines() for line in lines: myArray.append(line.split(" ")) 
0
source

Addendum to the accepted answer:

 with open("textFile.txt") as textFile: lines = [line.strip().split() for line in textFile] 

This will remove '\ n' if it is added at the end of each line.

0
source

Source: https://habr.com/ru/post/954798/


All Articles