How to write data from a .txt file into an array?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • k voller
    New Member
    • Jan 2011
    • 3

    #1

    How to write data from a .txt file into an array?

    Hi, I currently have a .txt file containing xyz coordinates of 10 particles which looks like:

    1.0,2.0,3.0
    4.0,5.0,6.0
    ...
    8.0,9.0,10.0

    and I want to turn this into an array which is the same shape as the data in the .txt file ie there would be 3 colums representing x,y,z coords and 10 rows representing the 10 particles. Im quite new to python so any help on how to do this would be great
  • bvdet
    Recognized Expert Specialist
    • Oct 2006
    • 2851

    #2
    Read the file, parse into a list of lists, type cast to float, initialize new array, iterate on data and add each number to array.

    Code:
    dataList = [[float(s) for s in item.strip().split(",")] for item in open("numpytest.txt").readlines()]
    rows = len(dataList)
    cols = len(dataList[0])
    arr1 = N.zeros([rows,cols], dtype=N.float64)
    for i, row in enumerate(dataList):
        for j, number in enumerate(row):
            arr1[i][j] = number

    Comment

    Working...