Getting Started with Python

Reading and analyzing data from a text file:

My gentle introduction to writing a Python script.  A script I needed to read in a log file and extract all inkjet printhead temperature values in Celcius recorded for the duration of the print run. Very simple. Open file and read each line of text, finding those whose string contains “Temperature”, for those that do strip away “Printhead Temperature (Celcius) = ” and strip away the newline character, leaving us with the raw temperature value printed on each line.

import string

file = open( 'C:\\Arrayjet\\MyLogfile.txt' )

for line in file.readlines():
   s = line

   if string.find( s, "Temperature" ) != -1:
      k = string.strip( s, "Printhead Temperature (Celcius) = " )
      k = string.strip( k, "\n" )
      print k

Raise a set of numbers to the power of 2; print the result:

import math

for i in range(0, 32): print int( math.pow( 2, i ) )

Reading / Writing from text files :

# open a file for reading, get the whole string
linestring = open( "C:\Text.txt", 'r' ).read()

# open text file for writing
outfile = open( "C:\OutText.txt", 'w' )

# output string to output file
outfile.write( linestring )

Read data from Excel, modify data and output to text file:

If you don’t already have it, download and install Python package for extracting data from Excel files. This is an example of making a small modification to all entries in a large tab-separated file, in order to make it compatible with other software I am using.

import xlrd
import string

# open spreadsheet
wb = xlrd.open_workbook( "C:\Arrayjet\Daryl Williams\cb5vance9thsept.xls" )

# get the first xls sheet by index
sh = wb.sheet_by_index( 0 )

# open up a text file for writing
outfile = open( "C:\Arrayjet\Daryl Williams\Out.txt", 'w' )

# iterate through rows and print their values. Add extra tab after first column
# and output all this to text file “Out.txt”

for rownum in range( sh.nrows ) :
   col0 = sh.cell( rownum, 0 ).value
   col1 = sh.cell( rownum, 1 ).value
   col2 = sh.cell( rownum, 2 ).value
   col3 = sh.cell( rownum, 3 ).value

   linestring = col0 + "\t" + col1 + "\t" + col2 + "\t" + col3 + "\n"
   outfile.write( linestring )



Leave a Reply