473,326 Members | 2,023 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,326 software developers and data experts.

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 27351
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

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

Similar topics

2
by: Randy Jackson | last post by:
Hello all. Okay, this seems really stupid, but it's driving me up the wall. I have a simple script I've written to log some information to a text file. Everything seems to be okay, the code...
1
by: JW | last post by:
Hi, Below is a description of what I would like to do. Would someone tell me if it is possible and if so, how? I have an array (presumably 'large') that is mallocced in a C function and its...
4
by: Faheem Mitha | last post by:
Dear People, I have the current modest goal. Given a user defined class, I want to creata an array of instances of that class. Consider the following class. class cell: def...
8
by: Bo Peng | last post by:
Dear list, I am writing a Python extension module that needs a way to expose pieces of a big C array to python. Currently, I am using NumPy like the following: PyObject* res =...
2
by: Kelly G. | last post by:
Hi all, I have a small problem in writing XML file from VB.net. I am trying to write the XML file using dataset. I am able to write the XML in sequential way(one node after other). I can write...
3
by: ishekar | last post by:
Hi, I have an application where i want to write data to a file, the data is being sent from an external source. I know the total size of the data and then i retrieve the data in small segments...
2
by: melanieab | last post by:
Hi, I'm trying to store all of my data into one file (there're about 140 things to keep track of). I have no problem reading a specific string from the array file, but I wasn't sure how to...
0
by: yogesh_anand | last post by:
Hi I am using sun solaris 5.9 operating system.Sometimes after reading from and while writing to file process size used to get increase.(it can be after 20th times 40 th time) I doesn't happen...
1
by: admol | last post by:
I'm using the following c# code to write a file string strVCard = vcg.Generate(); FileInfo fi = new FileInfo("" + firstn + " " + lastn + "" + ".vcf"); StreamWriter sw...
6
by: nubean19 | last post by:
Im new to the python programming and I wanted to know how to write an array using python
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
1
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
1
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.