473,395 Members | 1,530 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,395 software developers and data experts.

Reading from file to multiple lists

Sushi
19
Hello again all! (and happy easter if you are that way inclined)

I have this file called cameratrack.txt:
Expand|Select|Wrap|Line Numbers
  1. 0  (0  ,0  ,0  )
  2. 5  (5  ,0  ,0  )
  3. 10 (10 ,0  ,0  )
  4. 15 (15 ,5  ,0  )
  5. 20 (20 ,10 ,0  )
  6. 25 (25 ,15 ,0  )
  7. 30 (30 ,20 ,5  )
  8. 35 (30 ,25 ,10 )
  9. 40 (30 ,30 ,15 )
  10. 45 (30 ,30 ,20 )
  11. 50 (30 ,30 ,25 )
  12.  
And basically it is frame numbers and co-ordinates for a 3d object animation. I need to put each line's data into 4 different lists, which are frame, cordx, cordy and cordz. So for example line 2 would be frame[5], cordx[5], cordy[0], cordz[0]. I've got a solution with the following code:

Expand|Select|Wrap|Line Numbers
  1. #######camera tracking##########
  2. import string
  3.  
  4. frame = []    # The frame number of animation
  5. cordx = []    # The x position of object
  6. cordy = []    # The y position of object
  7. cordz = []    # The z position of object
  8.  
  9. f = open('C:\rest of filepath\cameratrack.txt', 'r')
  10.  
  11. data = f.readlines()        # Reading of the file
  12. datalength = len(data[0])    # Length of each line
  13. filelength = len(data)        # Length of file
  14.  
  15. print data
  16. print datalength
  17. print filelength
  18.  
  19. i = 0
  20.  
  21. while i != filelength:
  22.     frameppoints = [data[i][0], data[i][1], data[i][2]] 
  23.     framenum= float(string.join(frameppoints,''))    # Join to make frame number
  24.     frame.insert(i,framenum)                  # num inserted into list
  25.  
  26.  
  27.     xpoints = [data[i][4], data[i][5], data[i][6]]
  28.     xcords = float(string.join(xpoints,''))
  29.     cordx.insert(i,xcords)
  30.  
  31.     ypoints = [data[i][8],data[i][9], data[i][10]]
  32.     ycords = float(string.join(ypoints,''))
  33.     cordy.insert(i,ycords)
  34.  
  35.     zpoints = [data[i][12], data[i][13],data[i][14]]
  36.     zcords = float(string.join(zpoints,''))
  37.     cordz.insert(i,zcords)
  38.  
  39.     i+=1
  40.  
  41. print frame
  42. print cordx
  43. print cordy
  44. print cordz
  45.  
but was wondering if I've gone round a long way of doing this? I've got the string joining from this thread:
http://www.thescripts.com/forum/threadnav621769-2-10.html
but was wondering if anyone could see an obvious improvement on the code that Im missing? Any help would be appreciated, if not no worries!

Thanks!
Mel
Apr 8 '07 #1
13 1899
bartonc
6,596 Expert 4TB
Hi, Mel. I'll let bvdet grab this one (he loves these kind of exercises).

I will point out that the string module is a depricated module:
Expand|Select|Wrap|Line Numbers
  1. import string
  2. framenum= float(string.join(frameppoints,''))    # Join to make frame number
  3.  
should be
Expand|Select|Wrap|Line Numbers
  1. framenum= float(''.join(frameppoints))    # Join to make frame number
  2.  
The string module has some handy constants in it, but str type variables and literals have all the methods (defined as funcions in the string module) built into them.

Also, I prefer to iterate through a file object by line. And since you don't do anything fancy with the variable, i,
Expand|Select|Wrap|Line Numbers
  1. frame.insert(i,framenum)
is the same as
Expand|Select|Wrap|Line Numbers
  1. frame.append(framenum)
So this cleans up like this:
Expand|Select|Wrap|Line Numbers
  1. f = open('C:\rest of filepath\cameratrack.txt', 'r')
  2.  
  3. ## data = f.readlines()        # Reading of the file
  4. ## datalength = len(data[0])    # Length of each line
  5. f## ilelength = len(data)        # Length of file
  6.  
  7. ## print data
  8. ## print datalength
  9. ## print filelength   ### this is actually the length of the list created by readlines()
  10.  
  11. ## i = 0
  12.  
  13. for line in f:
  14.     print line
Apr 8 '07 #2
Sushi
19
Ah I see, that makes it neater. Will incorporate that into my code. Thanks barton!
Apr 8 '07 #3
bartonc
6,596 Expert 4TB
Ah I see, that makes it neater. Will incorporate that into my code. Thanks barton!
Sorry, I was editing my post so you missed some.
Apr 8 '07 #4
bvdet
2,851 Expert Mod 2GB
Here's a couple of ways.............
Data -
Expand|Select|Wrap|Line Numbers
  1. 0  (0  ,0  ,0  )
  2. 5  (5  ,0  ,0  )
  3. 10 (10 ,0  ,0  )
  4. 15 (15 ,5  ,0  )
  5. 20 (20 ,10 ,0  )
  6. 25 (25 ,15 ,0  )
  7. 30 (30 ,20 ,5  )
  8. 35 (30 ,25 ,10 )
  9. 40 (30 ,30 ,15 )
  10. 45 (30 ,30 ,20 )
  11. 50 (30 ,30 ,25 )
Expand|Select|Wrap|Line Numbers
  1. import re
  2.  
  3. fn = r'H:\TEMP\temsys\cameratrack.txt'
  4. patt = r'\d+'
  5. fList = open(fn).readlines()
  6. data = [re.findall(patt,item) for item in fList]
  7.  
  8. data1 = [[], [], [], []]
  9.  
  10. for i in range(4):
  11.     for item in data:
  12.         data1[i].append(int(item[i]))
  13.  
  14. for lst in data1:
  15.     print lst
  16.  
  17. print
  18. data2 = [[int(item[i]) for i in range(4) for item in data][j:j+len(data)] for j in range(0,len(data)*4,len(data))]
  19.  
  20. for lst in data2:
  21.     print lst
  22.  
  23. '''
  24. >>> [0, 5, 10, 15, 20, 25, 30, 35, 40, 45, 50]
  25. [0, 5, 10, 15, 20, 25, 30, 30, 30, 30, 30]
  26. [0, 0, 0, 5, 10, 15, 20, 25, 30, 30, 30]
  27. [0, 0, 0, 0, 0, 0, 5, 10, 15, 20, 25]
  28.  
  29. [0, 5, 10, 15, 20, 25, 30, 35, 40, 45, 50]
  30. [0, 5, 10, 15, 20, 25, 30, 30, 30, 30, 30]
  31. [0, 0, 0, 5, 10, 15, 20, 25, 30, 30, 30]
  32. [0, 0, 0, 0, 0, 0, 5, 10, 15, 20, 25]
  33. >>>
  34. '''
.....and to apply to your list names:
Expand|Select|Wrap|Line Numbers
  1. >>> varList = ['frame', 'coordx', 'coordy', 'coordz']
  2. >>> for i, v in enumerate(varList):
  3. ...     exec '%s = %s' % (v, data2[i])
  4. ...     
  5. >>> frame
  6. [0, 5, 10, 15, 20, 25, 30, 35, 40, 45, 50]
  7. >>> coordx
  8. [0, 5, 10, 15, 20, 25, 30, 30, 30, 30, 30]
  9. >>> coordy
  10. [0, 0, 0, 5, 10, 15, 20, 25, 30, 30, 30]
  11. >>> coordz
  12. [0, 0, 0, 0, 0, 0, 5, 10, 15, 20, 25]
  13. >>> 
  14.  
HTH :)
Apr 8 '07 #5
bvdet
2,851 Expert Mod 2GB
I actually prefer to compile data like this in a dictionary:
Expand|Select|Wrap|Line Numbers
  1. import re
  2.  
  3. fn = r'H:\TEMP\temsys\cameratrack.txt'
  4. patt = r'\d+'
  5. fList = open(fn).readlines()
  6. data = [re.findall(patt,item) for item in fList]
  7.  
  8. dataDict = dict(zip(['frame', 'coordx', 'coordy', 'coordz'], [[],[],[],[]]))
  9. for i, key in enumerate(dataDict):
  10.     for item in data:
  11.         dataDict[key].append(item[i])
  12.  
  13. for key in dataDict:
  14.     print '%s = %s' % (key, dataDict[key])
  15.  
  16. '''
  17. frame = ['0', '5', '10', '15', '20', '25', '30', '35', '40', '45', '50']
  18. coordz = ['0', '5', '10', '15', '20', '25', '30', '30', '30', '30', '30']
  19. coordy = ['0', '0', '0', '5', '10', '15', '20', '25', '30', '30', '30']
  20. coordx = ['0', '0', '0', '0', '0', '0', '5', '10', '15', '20', '25']
  21. '''
Apr 8 '07 #6
ghostdog74
511 Expert 256MB
From what I see at your output, you basically wants to "transpose" your data from column to row. here's another way,

Expand|Select|Wrap|Line Numbers
  1. store = [] #store results
  2. for line in open("cameratrack.txt"):
  3.     line = line.split(" ",1) 
  4.     coord = map(float,eval(line[1]))
  5.     frame = float(line[0])
  6.     coord.insert(0,frame)
  7.     store.append(coord)
  8. for i in  zip(*store):
  9.     print i
  10.  
output:
Expand|Select|Wrap|Line Numbers
  1. # ./test.py
  2. (0.0, 5.0, 10.0, 15.0, 20.0, 25.0, 30.0, 35.0, 40.0, 45.0, 50.0)
  3. (0.0, 5.0, 10.0, 15.0, 20.0, 25.0, 30.0, 30.0, 30.0, 30.0, 30.0)
  4. (0.0, 0.0, 0.0, 5.0, 10.0, 15.0, 20.0, 25.0, 30.0, 30.0, 30.0)
  5. (0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 5.0, 10.0, 15.0, 20.0, 25.0)
  6.  
Apr 9 '07 #7
ghostdog74
511 Expert 256MB
here's another way. assuming your data is all the same format. the open bracket is replaced with "," and the close bracket removed.
Expand|Select|Wrap|Line Numbers
  1. data = open("cameratrack").read().split("\n")
  2. result = [ eval(i.replace("(",",").replace(")","")) for i in data]
  3. for j in  zip(*result):
  4.     print j
  5.  
Apr 9 '07 #8
bvdet
2,851 Expert Mod 2GB
Well, I have learned something new today. Thanks GD. :) Here are a couple more variations using zip(*arg):
Lists -
Expand|Select|Wrap|Line Numbers
  1. import re
  2.  
  3. fn = 'cameratrack.txt'
  4. patt = r'\d+'
  5. varList = ['frame', 'coordx', 'coordy', 'coordz']
  6.  
  7. data = zip(*[re.findall(patt,item) for item in open(fn).readlines()])
  8.  
  9. for i, v in enumerate(varList):
  10.     exec '%s = %s' % (v, [float(i) for i in data[i]])
Dictionary -
Expand|Select|Wrap|Line Numbers
  1. data = zip(*[re.findall(patt,item) for item in open(fn).readlines()])
  2.  
  3. dataDict = {}
  4.  
  5. for i, key in enumerate(varList):
  6.     dataDict[key] = [float(i) for i in data[i]]
Apr 9 '07 #9
Sushi
19
Thanks for all the input guys!

I will have to have a proper look at the codes (i dont fully understand some of them on first glance) but will pop back if I have any queries!
Thanks again!
Mel
Apr 10 '07 #10
Sushi
19
Right I've had some time to look at these codes.

Expand|Select|Wrap|Line Numbers
  1. data = open("C:\Documents and Settings\Mel\Desktop\Python2\Blender\cameratrack.txt").read().split("\n")
  2. result = [ eval(i.replace("(",",").replace(")","")) for i in data]
  3. for j in  zip(*result):
  4.     print j
I think I understand the code, but cannot work out how to assign the list names so I can recall them later. I tried using some of bvdet code but ended up applying a line as a list:
Expand|Select|Wrap|Line Numbers
  1. data = open("C:\Documents and Settings\Mel\Desktop\Python2\Blender\cameratrack.txt").read().split("\n")
  2. result = [ eval(i.replace("(",",").replace(")","")) for i in data]
  3. for j in  zip(*result):
  4.     print j
  5.  
  6. varList = ['frame', 'coordx', 'coordy', 'coordz']
  7. for i, v in enumerate(varList):
  8.     exec '%s = %s' % (v, result[i])
  9.  
  10. print frame
  11. print coordx
  12. print coordy
  13. print coordz
I know its got something to do with the result[i] bit, but wasn't sure what to put there instead.

Expand|Select|Wrap|Line Numbers
  1.  
  2. import re
  3.  
  4. fn = 'C:\Documents and Settings\Mel\Desktop\Python2\Blender\cameratrack.txt'
  5. patt = r'\d+'
  6. varList = ['frame', 'coordx', 'coordy', 'coordz']
  7.  
  8. data = zip(*[re.findall(patt,item) for item in open(fn).readlines()])
  9.  
  10. for i, v in enumerate(varList):
  11.     exec '%s = %s' % (v, [float(i) for i in data[i]])
  12.  
  13. print frame
  14. print coordx
  15. print coordy
  16. print coordz
This was helpful but doesn't allow for negative numbers in the list e.g 5 (1,-10,10) comes out as 5, 1, 10, 10. Though I cant quite work out why!

If anyone could help or explain to me where Im going wrong that would be great thanks!
Mel
Apr 18 '07 #11
bartonc
6,596 Expert 4TB
I'll try to get some time to take a look. In the mean time, I'm just bumping this thread.

See ya, Mel.
Apr 19 '07 #12
bvdet
2,851 Expert Mod 2GB
Right I've had some time to look at these codes.



I think I understand the code, but cannot work out how to assign the list names so I can recall them later. I tried using some of bvdet code but ended up applying a line as a list:
Expand|Select|Wrap|Line Numbers
  1. data = open("C:\Documents and Settings\Mel\Desktop\Python2\Blender\cameratrack.txt").read().split("\n")
  2. result = [ eval(i.replace("(",",").replace(")","")) for i in data]
  3. for j in  zip(*result):
  4.     print j
  5.  
  6. varList = ['frame', 'coordx', 'coordy', 'coordz']
  7. for i, v in enumerate(varList):
  8.     exec '%s = %s' % (v, result[i])
  9.  
  10. print frame
  11. print coordx
  12. print coordy
  13. print coordz
I know its got something to do with the result[i] bit, but wasn't sure what to put there instead.


This was helpful but doesn't allow for negative numbers in the list e.g 5 (1,-10,10) comes out as 5, 1, 10, 10. Though I cant quite work out why!

If anyone could help or explain to me where Im going wrong that would be great thanks!
Mel
Replace the assignment to 'patt' with:
Expand|Select|Wrap|Line Numbers
  1. patt = r'-\d+|\d+'
This will look for negative numbers (numbers preceded with '-') and then look for positive numbers.
Apr 23 '07 #13
Sushi
19
Ah brilliant!
Thanks Bvdet!
Apr 25 '07 #14

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

Similar topics

7
by: David Bear | last post by:
I have a file that contains lists -- python lists. sadly, these are not pickled. These are lists that were made using a simple print list statement. Is there an easy way to read this file into a...
8
by: Mr. B | last post by:
I'm writing an app where I'm trying to look for and List all specific file 'types' found. So I point to a specific start top level Folder... and I want to drill down through ALL sub folders to...
6
by: KevinD | last post by:
assumption: I am new to C and old to COBOL I have been reading a lot (self teaching) but something is not sinking in with respect to reading a simple file - one record at a time. Using C, I am...
5
by: cybersangeeth | last post by:
Hi, I need to read 1KB each time from multiple files in a folder and pass it to a byte array in a struct to be sent through a socket. I'm a C++ newbie. I managed to read 1KB each time from one...
2
by: anchi.chen | last post by:
Hi People, Just wondering if any of you have ever come across any javascript examples that will allow one to drag and drop multiple items between lists? That is, users would be able to use the...
10
by: Tyler | last post by:
Hello All: After trying to find an open source alternative to Matlab (or IDL), I am currently getting acquainted with Python and, in particular SciPy, NumPy, and Matplotlib. While I await the...
0
by: jigsmshah | last post by:
I have a windows service developed in C#.I am reading the connection string from an ini file and also i am reading 3 image file from the bin directory. now the new requirement is that there will be...
16
by: WATYF | last post by:
Hi there... I have a huge text file that needs to be processed. At the moment, I'm loading it into memory in small chunks (x amount of lines) and processing it that way. I'd like the process to be...
4
by: Laharl | last post by:
My Operating Systems professor has assigned homework that basically boils down to implementing ls -lra, but with a different output format. In other words, list the files and subdirectories (and a...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...

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.