How to write an array to a file in python?

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

    How to write an array to a file in python?

    Hi, I have generated an array of random numbers and I'm trying to then write this array to a .txt file but the code I have written doesn't seem to do this correctly. I'm fairly new to python so any help on this would be great. Here is what I have so far:

    Code:
    import numpy as N
    import random
    
    def main():
       n=10
       size=1500
       initial=N.zeros([n,3], dtype=N.float64)
       filename="positions.txt"
    
       for i in range(n):
          for j in range(0,3):
             initial[i,j]=random.randrange(0,size)
       file=open(filename,'w')
       file.write(initial)
       file.close()
    Last edited by bvdet; Jan 30 '11, 06:26 PM. Reason: Fix code tags
  • bvdet
    Recognized Expert Specialist
    • Oct 2006
    • 2851

    #2
    You have to convert the array into a string before attempting to write it to a file. What should the file look like?

    Comment

    • bvdet
      Recognized Expert Specialist
      • Oct 2006
      • 2851

      #3
      You can also write the array to disk using array method tofile. The shape, type or endianness are not stored in the file.

      Comment

      • bvdet
        Recognized Expert Specialist
        • Oct 2006
        • 2851

        #4
        I would probably do it as shown below where arr is the array you created in your post:
        Code:
        f = open("numpytest.txt", "w")
        f.write("\n".join([",".join([str(n) for n in item]) for item in arr.tolist()]))
        f.close()
        The shape of the array is preserved, and you could recreate the array from the file.

        Comment

        • k voller
          New Member
          • Jan 2011
          • 3

          #5
          thanks that has worked well but I'm struggling to recreate the array from the .txt file. How can I now access the numbers in the file and put them into an array if they are not already part of a list or array?

          Comment

          • bvdet
            Recognized Expert Specialist
            • Oct 2006
            • 2851

            #6
            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...