By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
443,907 Members | 1,963 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 443,907 IT Pros & Developers. It's quick & easy.

How to write an array to a file in python?

P: 3
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
Share this Question
Share on Google+
5 Replies


bvdet
Expert Mod 2.5K+
P: 2,851
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
Expert Mod 2.5K+
P: 2,851
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
Expert Mod 2.5K+
P: 2,851
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

P: 3
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
Expert Mod 2.5K+
P: 2,851
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.