Join the Forum

Python Practice Dump

Wed, 7 Sep 2011

I get a bit rusty not having any personal projects to make with Python, I don't want to forget things so I try to practice once and a while. Here is a dump of code.


import os.path 
import sys
import glob
import re

# file name to open
fname = 'test.txt'

try:
	fobj = open(fname).read()
	print fobj
except IOError as e:
	print "The file doesn't exist, create it and re-run"
	sys.exit()

# show all lines in file	
for line in open(fname):
	for word in line.split():
		print word.upper()

# list a directory
dirlist = glob.glob('c:\\wamp\\*')
for item in dirlist:
	print item
	
# play with a string
s = '100 North Avenue'
print s
print s.replace('North', 'West')
print s[:-4] + s[-4:].replace('ue', 'xx')
print re.sub('West', 'East', s)

# play with regex
pattern = '[a-zA-Z]'
if (re.search(pattern, 'MyMommy') != None):
	print 'There is a match'
	
# play with loop
for i in range(10):
	if i % 2 == 0:
		print i