perl chomp equivalent in python?
Harry George
hgg9140 at seanet.com
Wed Mar 8 18:49:59 EST 2000
I've made a pyperl.py module which lets me do perl-like things,
including chomp. Here is the test code to give the flavor; actual
module is below.
#=============================
def test01():
ftn="test01"
debug(ftn,"---expansion---")
t1="Hello"
t2=", world"
t_3="good bye"
a1=['red','green',123]
txt=p("$t1$t2$123 at 123...$t_3 $t2 a1=@a1 modname=$modname")
#debug(ftn,"txt="+txt)
check(ftn,"expansion",txt=="Hello, world$123 at 123..."
"good bye , world a1= red green 123 modname=pyperl_test")
#=============================
def test02():
ftn="test02"
debug(ftn,"---strings---")
#---string manipulation---
txt="Hello, world"
check(ftn,"lc/uc",p.lc(txt)=="hello, world" and p.uc(txt)=="HELLO, WORLD")
t1=p.chop(txt+"\n")
t2=p.chop(txt)
t3=p.chomp(txt+"\n")
t4=p.chomp(txt)
#debug(ftn,"t1="+`t1`+" t2="+`t2`+" t3="+`t3`+" t4="+`t4`)
check(ftn,"chop/chomp",t1==txt and t2=="Hello, worl" \
and t3==txt and t4==txt)
#=============================
def test03():
ftn="test03"
debug(ftn,"---arrays---")
arr1=['red','green','blue']
check(ftn,"grep", p.grep("re.",arr1) == ['red','green'])
check(ftn,"join",p.join(':',arr1)=="red:green:blue")
check(ftn,"split",p.split(':',"red:green:blue")==arr1)
arr1=['red', 'green', 'blue']
check(ftn,"push", p.push(arr1,'yellow')==['red', 'green', 'blue','yellow'] \
and p.push(arr1,['orange','purple'])== \
['red', 'green', 'blue','yellow','orange','purple'])
check(ftn,"pop",p.pop(arr1)=='purple' and p.pop(arr1)=='orange' \
and arr1==['red', 'green', 'blue','yellow'])
arr1=['red', 'green', 'blue']
x,arr1=p.shift(arr1)
check(ftn,"shift", x=='red' and arr1==['green', 'blue'])
arr1=p.unshift(arr1,'yellow')
check(ftn,"unshift",arr1==['yellow','green', 'blue'])
#=============================
def test04():
ftn="test04"
debug(ftn,"---regular expressions---")
txt="Hello, world"
p.m("e(ll)",txt)
#debug(ftn,"p.PREMATCH="+p.PREMATCH+" p.MATCH="+p.MATCH+" p.POSTMATCH="+p.POSTMATCH)
check(ftn,"match",p.PREMATCH=='H' and p.MATCH=="ell" and p.POSTMATCH=="o, world" \
and p.S1=="ll")
t1=p.s("e(ll)",r'---\1---',txt)
#debug(ftn,"t1="+t1)
check(ftn,"substitute",t1=="H---ll---o, world")
t1=p.tr("el","EL",txt)
#debug(ftn,"t1="+t1)
check(ftn,"tr",t1=="HELLo, worLd")
#=============================
def test05():
ftn="test05"
debug(ftn,"---files---")
#---init some data---
currdir=p.cwd()
newdir=ftn
filename=ftn+"_file"
old=None
myfile=None
lines=[]
line=''
msg=p("test message for $ftn")
#---clean out old dir---
if p.d(newdir):
p.system("rm -rf $newdir")
else:
debug(ftn,p("$newdir not found"))
#--make new---
p.mkdir(newdir) or p.die("cannot make $newdir")
p.chdir(newdir) or p.die("cannot cd to $newdir")
myfile=p.open("> $filename")
if not myfile: p.die("cannot open $filename")
p.prt("before writing to file\n")
old=p.select(myfile)
p.prt("1: $msg\n")
p.prt("2: $msg\n")
p.prt("3: $msg\n")
myfile.close()
p.select(old)
p.prt("after writing to file\n")
myfile=p.open("< $filename")
if not myfile: p.die("cannot open $filename")
lines=p.input(myfile)
###myfile.close()
p.close(myfile)
for line in lines:
p.prt("line=$line\n")
myfile=p.open("< $filename")
while p.input1(myfile):
p.prt("line[$INPUT_LINE_NUMBER]=$_\n")
p.close(myfile)
#debug(ftn,p("currdir=$currdir"))
p.chdir(currdir)
#---file ops---
check(ftn,"file ops",p.e("go") and p.f("_") and p.r("_") and p.w("_") \
and p.x("_") and not p.d("_"))
#=============================
def test06():
ftn="test06"
debug(ftn,"---special variables---")
debug(ftn,p("argv=@ARGV"))
debug(ftn,p("pid=$PID, uid=$UID, euid=$EUID, gid=$GID, egid=$EGID"))
############################################
# pyperl.py
############################################
#!/usr/bin/env python
#/* pyperl.py
# * Copyright (C) 2000 Harry George
# *
# * This library is free software; you can redistribute it and/or
# * modify it under the terms of the GNU Library General Public
# * License as published by the Free Software Foundation; either
# * version 2 of the License, or (at your option) any later version.
# *
# * This library is distributed in the hope that it will be useful,
# * but WITHOUT ANY WARRANTY; without even the implied warranty of
# * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# * Library General Public License for more details.
# *
# * You should have received a copy of the GNU Library General Public
# * License along with this library; if not, write to the
# * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
# * Boston, MA 02111-1307, USA.
# */
"""
Usage: pyperl.py [options] filename
E.g., pyperl.py --aa --bb=xyz myfile
Options
-h,--help this message
-v,--version version
-a,--aa set boolean 'a'
-b,--bb set option bb to xyz
Revisions:
2000-02-22 Harry George initial version
"""
import sys,os,getopt,time,re,string,exceptions,commands,stat,types
#import parentclass
modname="pyperl"
__version__="0.1"
def debug(ftn,txt):
sys.stdout.write(modname+'.'+ftn+':'+txt+'\n')
sys.stdout.flush()
def fatal(ftn,txt):
sys.stdout.write(modname+'.'+ftn+':FATAL:'+txt+'\n')
sys.stdout.flush()
sys.exit(1)
def usage():
print __doc__
#===globals=======================
_linebreaks='\n\r\c'
alpha=string.letters+'_'
alphanum=alpha+string.digits
#==========================
class Dir:
#---------------------
def __init__(self,name):
self.lines=os.listdir(name)
#==========================
class File:
#---------------------
def __init__(self,perl,file,mode,formatname=""):
self.perl=perl
self.file=file
self.mode=mode
self.fileno=file.fileno()
self._cursor=0
self.OUTPUT_AUTOFLUSH=0 # $|
self.FORMAT_PAGE_NUMBER=0 # $%
self.FORMAT_LINES_PER_PAGE=60 # $=
self.FORMAT_LINES_LEFT=0 # $-
self.FORMAT_NAME=formatname # $"
self.FORMAT_TOP_NAME=formatname+"_TOP" # S^
if mode in ['r','r+']:
self.size=os.fstat(self.fileno)[stat.ST_SIZE]
self.buffer=file.read(self.size)
#------------------------
def flush(self):
self.file.flush()
#----------------------
def close(self):
self.file.close()
del self
#-------------------------
def readline(self):
ftn="readline"
sep=self.perl.INPUT_RECORD_SEPARATOR; seplen=len(sep)
buff=self.buffer; start=self._cursor; end=len(buff)-seplen
if start>=end:
return None
ndx=start
ch=sep[0]
while 1:
while buff[ndx] != ch and ndx < end:
ndx=ndx+1
if ndx==end:
break
elif buff[ndx:ndx+seplen]==sep:
end=ndx
break
self._cursor=end+seplen
line=buff[start:end]
return line
#-------------------------
def readlines(self):
sep=self.perl.INPUT_RECORD_SEPARATOR
lines=string.split(self.buffer,sep)
return lines[:-1]
#------------------------
def writeline(self,line):
sep=self.perl.OUTPUT_RECORD_SEPARATOR
self.file.write(line+sep)
if self.OUTPUT_AUTOFLUSH:
self.file.flush()
#------------------------
def writelines(self,lines):
sep=self.perl.OUTPUT_RECORD_SEPARATOR
for line in lines:
self.file.write(line+sep)
if self.OUTPUT_AUTOFLUSH:
self.file.flush()
#==========================
class PyPerl:
#----------------------------
def __init__(self):
#---special variables---
self.STDIN = File(self,sys.stdin,"")
self.STDOUT= File(self,sys.stdout,"w")
self.STDERR= File(self,sys.stderr,"w")
self.ARGV = sys.argv
self.ENV = os.environ
self.ERRORNO=0
self.INPUT_LINE_NUMBER=0 # $.
self.INPUT_RECORD_SEPARATOR=os.linesep # $/
self.OUTPUT_FIELD_SEPARATOR=' ' # $,
self.OUTPUT_RECORD_SEPARATOR='' # $\
self.LIST_SEPARATOR=' ' # $"
self.SUBSCRIPT_SEPARATOR="\034" # $;
self.FORMAT_FORMFEED='\f' # $^L
self.FORMAT_LINE_BREAK_CHARACTERS=" \n-" # $:
self.ACCUMULATOR=[] # $^A
self.CHILD_ERROR=0 # $?
self.OS_ERROR=0 # $!
self.EVAL_ERROR=0 # $@
self.PID=os.getpid() # $$
self.UID=os.getuid() # $<
self.EUID=os.geteuid() # $>
self.GID=os.getgid() # $(
self.EGID=os.getegid() # $)
self.S0=sys.argv[0] # $0 (program name)
self.S_= None # $_
self.A_= [] # @_
#---internal memory---
self._output = self.STDOUT # "selected" output
self._stat = None # results of a stat lookup
#---regexp results---
self.S1='';self.S2='';self.S3='';self.S4='';self.S5=''
self.S6='';self.S7='';self.S8='';self.S9=''
self.PREMATCH='';self.MATCH='';self.POSTMATCH=''
#---renames for functions---
self.m=self.match
self.s=self.substitute
self.tr=self.translate
#-----------------------------
# utilities
#-----------------------------
def __call__(self,txt):
"""expand inline '$' and '@"""
return self._ex(txt)
#-----------------------------
def _ex(self,txt):
"""expand inline '$' and '@"""
newtxt=''
#---get the caller's dictionaries---
try:
raise None
except:
c=sys.exc_info()[2].tb_frame.f_back.f_back
#debug(ftn,"caller="+`c`)
local_dict=c.f_locals
#debug(ftn,"local_dict="+`local_dict`)
global_dict=c.f_globals
#debug(ftn,"global_dict="+`global_dict`)
#---scan the string---
ndx=0
maxndx=len(txt)-1
while ndx<=maxndx:
if txt[ndx]=='$':
ndx=ndx+1
if txt[ndx] not in alpha:
newtxt=newtxt+'$'
continue
#---get the name---
start=ndx
while ndx<=maxndx and txt[ndx] in alphanum:
ndx=ndx+1
name=txt[start:ndx]
#debug(ftn,"name=|"+name+"|")
#---we have a name, now lookup its value---
if local_dict.has_key(name):
val=local_dict[name]
elif global_dict.has_key(name):
val=global_dict[name]
elif self.__dict__.has_key(name):
val=self.__dict__[name]
elif name == '_':
val=self.S_
else:
val='$'+name
#---use the value---
newtxt=newtxt+str(val)
elif txt[ndx]=='@':
ndx=ndx+1
if txt[ndx] not in alpha:
newtxt=newtxt+'@'
continue
#---get the name---
start=ndx
while ndx<=maxndx and txt[ndx] in alphanum:
ndx=ndx+1
name=txt[start:ndx]
#---we have a name, now lookup its value---
if local_dict.has_key(name):
val=local_dict[name]
elif global_dict.has_key(name):
val=global_dict[name]
elif self.__dict__.has_key(name):
val=self.__dict__[name]
elif name == '_':
val=self.A_
else:
val='$'+name
#---use the value---
for item in val:
newtxt=newtxt+self.LIST_SEPARATOR+str(item)
else:
newtxt=newtxt+txt[ndx]
ndx=ndx+1
return newtxt
#-----------------------------
def cat(*args):
"""perl default is no spaces"""
return string.join(args,'')
#-----------------------------
def ERRORNO_str(self):
# $! is error status
return os.strerror(self.ERRORNO)
#---------------------
# strings
#---------------------
#---------------------
def chomp(self,data=None):
def strip(x):
orig_len=len(x)
cnt=0
for i in xrange(len(x)-1,0,-1):
if x[i] not in _linebreaks:
x=x[:i+1]
cnt=orig_len-i-1
break
return x,cnt
if not data: data=self.A_
if isinstance(data,types.StringType):
data,cnt=strip(data)
return data
elif isinstance(data,types.ListType):
cnt=0
for line in data:
line,c=strip(line)
cnt=cnt+c
return data
#---------------------
def chop(self,data=None):
if not data: data=self.A_
ch=''
if isinstance(data,types.StringType):
if 1:
ch=data[-1]
return data[:-1]
elif isinstance(data,types.ListType):
ch=''
for line in data:
ch=line[-1]
line=line[:-1]
return data
#--------------------
def lc(self,txt):
return string.lower(txt)
#-----------------------
def uc(self,txt):
return string.upper(txt)
#---------------------
# regular expressions
#---------------------
#--------------------
def match(self,pattern,data=None):
if not data: data=self.S_
mem=re.search(pattern,data)
(self.S1,self.S2,self.S3,self.S4,self.S5,self.S6,\
self.S7,self.S8,self.S9)=['','','','','','','','','']
self.PREMATCH=''
self.MATCH=''
self.POSTMATCH=''
mem=re.search(pattern,data)
if mem:
self.PREMATCH=data[:mem.start()]
self.MATCH=data[mem.start():mem.end()]
self.POSTMATCH=data[mem.end():]
grps=mem.groups()
grplen=len(grps)
if grplen > 8: self.S9=grps[8]
if grplen > 7: self.S8=grps[7]
if grplen > 6: self.S7=grps[6]
if grplen > 5: self.S6=grps[5]
if grplen > 4: self.S5=grps[4]
if grplen > 3: self.S4=grps[3]
if grplen > 2: self.S3=grps[2]
if grplen > 1: self.S2=grps[1]
if grplen > 0: self.S1=grps[0]
self.A_=[self.S1,self.S2,self.S3,self.S4,self.S5,self.S6,\
self.S7,self.S8,self.S9]
return self.A_
#---------------------
def substitute(self,pattern,replacement,data=None,options=''):
if data==None: data=self.A_
data,cnt=re.subn(pattern,replacement,data)
self.A_=data
return self.A_
#----------------------
def translate(self,oldchars,newchars,data):
oldtxt=data
if oldtxt==None: oldtxt=self.S_
#---init the trans table; extend lastch of newchars as needed---
oldlen=len(oldchars)
newlen=len(newchars)
lastch=newchars[-1]
for i in range(newlen,oldlen):
newchars.append(lastch)
trans=string.maketrans(oldchars,newchars)
#---do the trsnalation---
self.S_=string.translate(oldtxt,trans)
return self.S_
#---------------------
# arrays and hashes
#---------------------
#---------------------
def grep(self,pattern,arr=None):
if not arr: arr=self.A_
pat=re.compile(pattern)
return filter(pat.search,arr)
#--------------------
def join(self,marker=':',arr=None):
if not arr: arr=self.A_
self.S_=string.join(arr,marker)
return self.S_
#---------------------
def pop(self,arr=None):
if not arr: arr=self.A_
return arr.pop()
#---------------------
def push(self,arr,data):
if isinstance(data,types.ListType):
arr.extend(data)
elif isinstance(data,types.StringType):
arr.append(data)
else:
arr.append(str(data))
return arr
#---------------------
def shift(self,arr=None):
if not arr: arr=self.A_
val=arr[0]
arr=arr[1:]
self.A_=arr
return val,arr
#---------------------
def split(self,sep=':',data=None,maxcnt=0):
if not data: data=self.S_
self.A_=string.split(data,sep,maxcnt)
return self.A_
#---------------------
def unshift(self,arr,data):
arr.insert(0,data)
return arr
#---------------------
# execution
#---------------------
def bq(self,cmd):
"""bq=backquote"""
return commands.getoutput(self._ex(cmd))
#----------------------
def caller(self,txt):
ftn="caller"
try:
raise None
except:
c=sys.exc_info()[2].tb_frame.f_back
debug(ftn,"caller="+`c`)
return c.co_name, c.co_filename, c.co_firstlineno
#----------------------
def system(self,cmd):
try:
os.system(self._ex(cmd))
except: return 0
else: return 1
#---------------------
# file ops
#---------------------
#---------------------
def _get_stat(self,path):
if not path: path=self.S_
if path=='_':
return 1
else:
try:
self._stat=os.stat(path)
except:
return 0
return 1
#--------------------
def b(self,path=None):
if not self._get_stat(self._ex(path)): return None
return stat.S_ISBLK(self._stat[stat.ST_MODE])
#--------------------
def c(self,path=None):
if not self._get_stat(self._ex(path)): return None
return stat.S_ISCHR(self._stat[stat.ST_MODE])
#--------------------
def d(self,path=None):
if not self._get_stat(self._ex(path)): return None
return stat.S_ISDIR(self._stat[stat.ST_MODE])
#--------------------
def e(self,path=None):
if not self._get_stat(self._ex(path)): return None
return self._get_stat(self._ex(path))
#--------------------
def f(self,path=None):
if not self._get_stat(self._ex(path)): return None
return stat.S_ISREG(self._stat[stat.ST_MODE])
#--------------------
def l(self,path=None):
if not self._get_stat(self._ex(path)): return None
return stat.S_ISLINK(self._stat[stat.ST_MODE])
#--------------------
def p(self,path=None):
if not self._get_stat(self._ex(path)): return None
return stat.S_ISFIFO(self._stat[stat.ST_MODE])
#--------------------
def s(self,path=None):
if not self._get_stat(self._ex(path)): return None
return stat.S_ISSOCK(self._stat[stat.ST_MODE])
#---------------------
def r(self,path=None):
if not self._get_stat(self._ex(path)): return None
st=self._stat
mode=st[stat.ST_MODE]
if (mode & 0004):
return 1
elif os.getegid()==st[stat.ST_GID] and (mode & 0040):
return 1
elif os.geteuid()==st[stat.ST_UID] and (mode & 0400):
return 1
else:
return 0
#---------------------
def R(self,path=None):
if not self._get_stat(self._ex(path)): return None
st=self._stat
mode=st[stat.ST_MODE]
if (mode & 0004):
return 1
elif os.getgid()==st[stat.ST_GID] and (mode & 0040):
return 1
elif os.getuid()==st[stat.ST_UID] and (mode & 0400):
return 1
else:
return 0
#---------------------
def w(self,path=None):
if not self._get_stat(self._ex(path)): return None
st=self._stat
mode=st[stat.ST_MODE]
if (mode & 0002):
return 1
elif os.getegid()==st[stat.ST_GID] and (mode & 0020):
return 1
elif os.geteuid()==st[stat.ST_UID] and (mode & 0200):
return 1
else:
return 0
#---------------------
def W(self,path=None):
if not self._get_stat(self._ex(path)): return None
st=self._stat
mode=st[stat.ST_MODE]
if (mode & 0002):
return 1
elif os.getgid()==st[stat.ST_GID] and (mode & 0020):
return 1
elif os.getuid()==st[stat.ST_UID] and (mode & 0200):
return 1
else:
return 0
#---------------------
def x(self,path=None):
if not self._get_stat(self._ex(path)): return None
st=self._stat
mode=st[stat.ST_MODE]
if (mode & 0001):
return 1
elif os.getegid()==st[stat.ST_GID] and (mode & 0010):
return 1
elif os.geteuid()==st[stat.ST_UID] and (mode & 0100):
return 1
else:
return 0
#---------------------
def X(self,path=None):
if not self._get_stat(self._ex(path)): return None
st=self._stat
mode=st[stat.ST_MODE]
if (mode & 0001):
return 1
elif os.getgid()==st[stat.ST_GID] and (mode & 0010):
return 1
elif os.getuid()==st[stat.ST_UID] and (mode & 0100):
return 1
else:
return 0
#---------------------
def z(self,path=None):
if not self._get_stat(self._ex(path)): return None
return self._stat[stat.ST_SIZE]==0
#---------------------
# files and dirs
#---------------------
def chdir(self,dir):
dir=self._ex(dir)
try:
os.chdir(dir)
except (OSError,IOError), e:
self.ERRORNO=e
return 0
else: return 1
#---------------------
def chmod(self,mode,*paths):
try:
for path in paths:
path=self._ex(path)
os.chmod(path,mode)
except IOError, e:
self.ERRORNO=e
return 0
else: return 1
#--------------------
def chown(self,uid,gid,*paths):
try:
for path in paths:
path=self._ex(path)
os.chown(path,uid,pid)
except: return 0
else: return 1
#--------------------
def close(self,file):
file.close()
#--------------------
def closedir(self,dir):
del dir
#--------------------
def cwd(self):
return os.getcwd()
#--------------------
def die(self,txt):
fatal('die',self._ex(txt))
#--------------------
def eof(self,file):
"""current loc == end loc, both with 0 offset"""
return f.seek(0,1) == f.seek(0,2)
#--------------------
def input(self,file=None,arr=None):
"""equiv of <file> in array context"""
if not file: file=self.STDIN
if file==self.STDIN:
self.A_=sys.stdin.readlines()
else:
if arr:
arr=file.readlines()
return arr
else:
self.A_=file.readlines()
return self.A_
#--------------------
def input1(self,file=None):
"""equiv of <file> in scalar context"""
if not file: file=self.STDIN
if file==self.STDIN:
self.S_=sys.stdin.readline()
else:
self.S_=file.readline()
if self.S_:
self.INPUT_LINE_NUMBER=self.INPUT_LINE_NUMBER+1
return self.S_
#--------------------
def mkdir(self,dir,mode=0777):
dir=self._ex(dir)
try:
os.mkdir(dir,mode)
except (OSError,IOError), e:
self.ERRORNO=e
return 0
else: return 1
#--------------------
def open(self,path=""):
ftn="open"
path=self._ex(path)
path=string.strip(path)
mem=re.search(r'([+\|<>]+)\s*([A-Za-z0-9_\-\.]+)\s*(\|)?$',path)
if not mem:
return None
m1,m2,m3=mem.groups()
#debug(ftn,"m1=%(m1)s, m2=%(m2)s, m3=%(m3)s." % locals())
#---normal opens---
mode={'<':"r", '+<':"r+", '>':"w", '+>':"w+", \
'>>':"a", '+>>':"a+"}
if mode.has_key(m1):
pymode=mode[m1]
file=open(m2,pymode)
return File(self,file,pymode)
#---check for pipes---
if m1=='|':
return File(self,os.popen(m2,"r"),"r")
if m3 and m3=='|':
return File(self,os.popen(m2,"w"),"w")
#--------------------
def opendir(self,dir,name):
return Dir(name)
#---------------------
def prt(self,*args):
f=self._output
if len(args)==0:
f.write(self._ex(self.S_))
return
if isinstance(args[0],File):
f=args[0]
args=args[1:]
if len(args)==0:
f.writeline(self._ex(self.S_))
return
for arg in args:
f.writeline(self._ex(arg))
#---------------------
def readdir(self,dir):
return dir.lines
#---------------------
def rmdir(self,path):
os.rmdir(path)
#---------------------
def select(self,file):
tmp=self._output
self._output=file
return tmp
#-----------------------
def unlink(self,path):
try:
os.unlink(path)
except (OSError,IOError),e:
self.ERRORNO=e
return 0
else: return 1
#=================================
def test():
ftn="test"
debug(ftn,"begin")
p=PyPerl()
p.print_("hello," , " world\n")
testscript="pyperl_test.py"
if p.e(testscript):
p.system(testscript)
#---main-----------
#exemplars; tweak as needed
opt_a=0 #boolean arg, default is false
opt_b=None #string arg, default is undefined
#positional args, default is empty
pargs=[]
if __name__ == '__main__':
ftn = "main"
opts,pargs=getopt.getopt(sys.argv[1:],'hvab:',
['help','version','aa','bb='])
for opt in opts:
if opt[0]=='-h' or opt[0]=='--help':
usage()
sys.exit(0)
elif opt[0]=='-v' or opt[0]=='--version':
print modname+": version="+version
elif opt[0]=='-a' or opt[0]=='--aa':
opt_a=1
elif opt[0]=='-b' or opt[0]=='--bb':
opt_b=opt[1]
#---make the object and run it---
test()
############################################
Fred Gansevles <gansevle at cs.utwente.nl> writes:
> Nathan Clegg wrote:
>
> > On 10-Feb-2000 Will Ware wrote:
> > > I often find myself doing things like this inside 'for
> > > ...readlines():'
> > > loops, and it always strikes me as cheesy and inelegant. It'd be
> > > kinda
> > > cool if readlines() could take an argument that meant to strip away
> > > any trailing whitespace.
> >
> > Why not use string.rstrip() ???
> >
> > for line in map(string.rstrip, f.readlines()):
> > ....
> >
> > ----------------------------------
> > Nathan Clegg
> > nathan at islanddata.com
>
> I always use
>
> for line in string.split (open (file).read(), '\n'):
> ....
>
>
--
Harry George
hgg9140 at seanet.com
More information about the Python-list
mailing list