Reading a file into a multidimensional array with Python

前端 未结 5 1212
迷失自我
迷失自我 2021-02-20 02:56

If I have a text file like this:

Hello World
How are you?
Bye World

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



        
5条回答
  •  南笙
    南笙 (楼主)
    2021-02-20 03:30

    A good answer would be :

    def read_text(path):
        with open(path, 'r') as file:
            line_array = file.read().splitlines()
            cell_array = []
            for line in line_array:
                cell_array.append(line.split())
            print(cell_array)
    

    Which is optimized for readability.

    But python syntax let's us use less code:

    def read_text(path):
        with open(path, 'r') as file:
            line_array = file.read().splitlines()
            cell_array = [line.split() for line in line_array]
            print(cell_array)
    

    And also python let's us do it only in one line!!

    def read_text(path):
        print([[item for item in line.split()] for line in open(path)])
    

提交回复
热议问题