468,549 Members | 2,218 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 468,549 developers. It's quick & easy.

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:

Expand|Select|Wrap|Line Numbers
  1. import numpy as N
  2. import random
  3.  
  4. def main():
  5.    n=10
  6.    size=1500
  7.    initial=N.zeros([n,3], dtype=N.float64)
  8.    filename="positions.txt"
  9.  
  10.    for i in range(n):
  11.       for j in range(0,3):
  12.          initial[i,j]=random.randrange(0,size)
  13.    file=open(filename,'w')
  14.    file.write(initial)
  15.    file.close()
  16.  
  17.  
Jan 30 '11 #1
5 26618
bvdet
2,851 Expert Mod 2GB
You have to convert the array into a string before attempting to write it to a file. What should the file look like?
Jan 30 '11 #2
bvdet
2,851 Expert Mod 2GB
You can also write the array to disk using array method tofile. The shape, type or endianness are not stored in the file.
Jan 30 '11 #3
bvdet
2,851 Expert Mod 2GB
I would probably do it as shown below where arr is the array you created in your post:
Expand|Select|Wrap|Line Numbers
  1. f = open("numpytest.txt", "w")
  2. f.write("\n".join([",".join([str(n) for n in item]) for item in arr.tolist()]))
  3. f.close()
The shape of the array is preserved, and you could recreate the array from the file.
Jan 30 '11 #4
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?
Jan 30 '11 #5
bvdet
2,851 Expert Mod 2GB
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.

Expand|Select|Wrap|Line Numbers
  1. dataList = [[float(s) for s in item.strip().split(",")] for item in open("numpytest.txt").readlines()]
  2. rows = len(dataList)
  3. cols = len(dataList[0])
  4. arr1 = N.zeros([rows,cols], dtype=N.float64)
  5. for i, row in enumerate(dataList):
  6.     for j, number in enumerate(row):
  7.         arr1[i][j] = number
Jan 30 '11 #6

Post your reply

Sign in to post your reply or Sign up for a free account.

Similar topics

2 posts views Thread by Randy Jackson | last post: by
4 posts views Thread by Faheem Mitha | last post: by
2 posts views Thread by Kelly G. | last post: by
3 posts views Thread by ishekar | last post: by
2 posts views Thread by melanieab | last post: by
1 post views Thread by admol | last post: by
reply views Thread by NPC403 | last post: by
1 post views Thread by UniDue | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.