Thursday, September 24, 2009

Python string methods for case conversion


Few important python string methods for case conversion.

swapcase()
Return a copy of the string with uppercase characters converted to lowercase and vice versa.

upper()
Return a copy of the string converted to uppercase.

title()
Return a titlecased version of the string: words start with uppercase characters, all remaining cased characters are lowercase.

lower()
Return a copy of the string converted to lowercase.

capitalize( )
Return a copy of the string with only its first character capitalized.

On python prompt:

>>> s='www.ExAmple.cOM'
>>> s
'www.ExAmple.cOM'
>>> s.swapcase()
'WWW.eXaMPLE.Com'
>>> s.upper()
'WWW.EXAMPLE.COM'
>>> s.lower()
'www.example.com'
>>> s.title()
'Www.Example.Com'
>>> s.capitalize()
'Www.example.com'
>>> st="This is the Best"
>>> st.capitalize()
'This is the best'
>>> st.title()
'This Is The Best'

Tuesday, September 15, 2009

Find text string in file in Python

Each line of file "querymapping.txt" contains two fields.
1st field is a sql query and
2nd one is a filename where the output of that sql query is stored.

$ cat querymapping.txt
select * from tab_fan_details;|/tmp/query7
select * from tab_fan_speed_details;|/tmp/query4
select * from tab_fan_spec;|/tmp/query1

Required:

Write a python function to look-up a particular sql query (send as 1st argument to the script ) in the querymapping.txt file and return the query output filename. If no match found return default filename as '/tmp/query0'

The python program:

import sys
default='/tmp/query0'

def lookupfilename(query):
'''Lookup query output filename from query'''
for line in open('querymapping.txt'):
if query.strip() in line.strip().split("|")[0]:
return line.strip().split("|")[1]
return default

fname=lookupfilename(sys.argv[1])
print fname

Executing the script:

$ python qlookup.py "select * from tab_fan_speed_details;"
/tmp/query4

$ python qlookup.py "select * from tab_fan_speed_details_new;"
/tmp/query0

Related post:

- Lookup file in python using dictionary

Sunday, September 13, 2009

Print file content to output - Python

Required: Write a python program to print the content of a file to output (same as Linux/UNIX cat command do)

Way1: Using file.read file object in python

import sys,os.path

if len(sys.argv) < 2:
print 'No file specified'
sys.exit()
else:
try:
f = open(sys.argv[1], 'r')
print f.read(),
f.close()
except IOError:
print "File" + sys.argv[1] + "does not exist."


Execute it this way: To print the contents of file.txt to the output.

$ python cat-read.py file.txt


Way2: Another similar python program using file.readline

import sys

def readfile(fname):
f = file(fname)
while True:
line = f.readline()
if len(line) == 0:
break
print line.strip() #Avoid strip: print line,
f.close()

if len(sys.argv) < 2:
print 'No file specified'
sys.exit()
else:
readfile(sys.argv[1])


Read about python file()
In python 3.0 file() is removed.

Related concepts:

Wednesday, September 2, 2009

Print last instance of file - python example

Input file:

$ cat data.txt
k:begin:0
i:0:66
i:1:76
k:end:0
k:begin:7
i:0:55
i:1:65
i:2:57
k:end:7
k:begin:2
i:0:10
i:1:0
k:end:7
k:begin:2
i:0:46
k:end:7
k:begin:9
i:0:66
i:1:56
i:2:46
i:3:26
k:end:7

Required: Print last instance of the above file. One instance being from "k:begin" to "k:end"

The python program:

result =[]
all = open("data.txt").readlines()
for line in all[::-1]: #start from last ;proceed up
f=line.split(":")
if f[0]=="k" and f[1]=="end":
continue
elif f[0]=="k" and f[1]=="begin":
break
else: result.append(line)
print result
print "\nlast instance is\n"
print ''.join(result[::-1]) #reverse


Executing it:

$ python ins.py
['i:3:26\n', 'i:2:46\n', 'i:1:56\n', 'i:0:66\n']

last instance is

i:0:66
i:1:56
i:2:46
i:3:26



Related post:
- Print first few instances from file using python

Tuesday, September 1, 2009

Truncate file extension using python glob

My current directory contains the following 2 files.

$ ls -1
20061117.dat.dat
details.dat.dat.dat

Required: Move(rename) the above files to single .dat extension (e.g. details.dat.dat.dat to details.dat)
The python code using glob module:

>>> import os,glob
>>> for file in glob.glob("*.dat"):
... newF=".".join(file.split(".")[:2])
... os.rename(file,newF)
...

Now:

$ ls -1
20061117.dat
details.dat


Using glob module we can use wildcards with Python according to the rules used by the Unix shell. More about it can be found here

Few more examples:

# lists all files in the current directory
glob.glob('*')

# returns all .dat extension files
glob.glob('*.dat')

# lists all files starting with a letter, followed by 3 characters (numbers, letters) and any ending.
glob.glob('[a-z]???.*')