Reading file string into an array (In a pythonic way)

后端 未结 5 792
礼貌的吻别
礼貌的吻别 2020-12-06 03:39

I\'m reading lines from a file to then work with them. Each line is composed solely by float numbers.

I have pretty much everything sorted up to convert the lines in

5条回答
  •  太阳男子
    2020-12-06 04:22

    If you want a numpy array and each row in the text file has the same number of values:

    a = numpy.loadtxt('data.txt')
    

    Without numpy:

    with open('data.txt') as f:
        arrays = list(csv.reader(f, delimiter=' ', quoting=csv.QUOTE_NONNUMERIC))
    

    Or just:

    with open('data.txt') as f:
        arrays = [map(float, line.split()) for line in f]
    

提交回复
热议问题