0

I have an executable which gives an output like the following,

Posture state: 3         Posture side: 0   
Posture state: 3         Posture side: 0  
Posture state: 3         Posture side: 0  
Posture state: 3         Posture side: 0  
Posture state: 3         Posture side: 2  
Posture state: 3         Posture side: 2  
Posture state: 3         Posture side: 2  
Posture state: 3         Posture side: 2  
Posture state: 3         Posture side: 2  
Posture state: 3         Posture side: 2  

I tried to pipe the output to a csv file as follows, but the formatting is not preserved. More specifically - the space between Posture state and Posture side is not applied.

./posture.exe > posture_result_acc5.csv

I want the Posture state to go to one column of the csv file and posture side to the next column. How can this be done?

3
  • You need a comma after the Posture State value. What is the executable, and do you have the source code for it?
    – Carl H
    Mar 5, 2015 at 17:09
  • The space between the two columns cannot be used as the delimiter?
    – Naveen
    Mar 5, 2015 at 17:15
  • You could use tabs as the delimiters - but then it wouldn't be a comma separated file Mar 5, 2015 at 23:18

1 Answer 1

2

Paste this into a file and save it as posture.py

for line in open('temp.txt','r'):
    a,b,c=line.split(':')
    state=b.replace('Posture side','').replace(' ','')
    side=c.rstrip().replace(' ','')
    print('%s,%s' %(state,side))

And then

./posture.exe > temp.txt
python posture.py > posture_result_acc5.csv

How it works.

The output from your posture.exe is written to a temporary file.

The Python script reads the temp file one line at a time.

Each line is split into three chunks by splitting on the colons.

The 'state' value is the middle chunk with the spaces and 'Posture side' removed.

The 'side' value is the third chunk with the spaces and newline character removed.

These are printed as a comma seperated pair.

The output is redirected into the csv file.

If you want the words as well as the value, then change the last line of the Python script to

print('Posture state: %s,Posture side: %s' %(state,side))

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.