View Full Version : Python to edit text files

09 September 2010, 03:23 PM
I am currently using a shell script using "grep" and "awk" to edit data text files. I'd like to do this using python if possible

Would anyone care to demonstrate how I could extract just the float values from the text below? Or let me know if it is awkward to be doing this kind of task in Python.

Adobe After Effects 8.0 Keyframe Data

Units Per Second 29.97
Source Width 900
Source Height 506
Source Pixel Aspect Ratio 1
Comp Pixel Aspect Ratio 1

Effects Sound Keys #1 Output 1 #22
131 0.263784
132 0.277537
133 0.342596
134 0.325534
135 0.246398
136 0.234771
137 0.304555
138 0.29599

I want:


Thanks for reading!

09 September 2010, 03:35 PM
reading a text file is extremely simple and straightforward at the basic level, but in your file you have several other floats (8.0, 29.97, etc..) so the hardest thing to do is to decide how your function will find and extract the correct floats when reading the file.

Looking at your example I'd say any line that contains 2 tokens, the first of which is an int and the second of which is a float should work, but I have no idea what permutations your text files may come in. only you will know that for sure. You could alternatively wait for the line with just "Frame" in it and then start reading floats.... the choice is down to you.


09 September 2010, 03:41 PM
here's a very basic example Wolfy:

textFile = 'c:/data.txt'
file = open(textFile,'r')
for line in file.readlines():
tokens = line.split()
if len(tokens) == 2:
print tokens[1]
it obviously needs more error-checking for the floats and such, but it's an example of how easy it is to parse a text file.

CGTalk Moderation
09 September 2010, 03:41 PM
This thread has been automatically closed as it remained inactive for 12 months. If you wish to continue the discussion, please create a new thread in the appropriate forum.