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

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

P: 3
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
Jan 30 '11 #1
Share this Question
Share on Google+
1 Reply


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 #2

Post your reply

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