Moving from perl to python: questions

Gerrit Holl gerrit.holl at pobox.com
Wed Feb 16 14:14:32 EST 2000


Nathan Clegg wrote on 950687221:
> 
> On 16-Feb-2000 David R. Favor wrote:
> >   2) How to implement a no-frills file slurp() function
> 
> 
> import string
> 
> def slurp(filename):
>  print filename
>  try:
>   f = open(filename, 'r')
>  # catch whichever exceptions you fancy, here
> 
>  # rstrip will strip all whitespace off the right side,
>  # much like chomp
>  lines = map(string.rstrip, f.readlines())
> 
>  f.close
> 
>  return lines

Sorry, but I need to correct you.

First, string.rstrip() might strip unwanted whitespace too; it does
not only strip the newline. You'll need to check wheter the last character
is a newline, and if so, strip it manually, like:

# PSEUDO CODE
for line in lines:
    if line[-1] == '\n':
        line = line[:-1]

Second: f.close is a function, so you'll need to append two parantheses:
f.close()

Third: a one-space indentation is considered Bad Style(tm)

regards,
Gerrit.

-- 
Homepage: http://www.nl.linux.org/~gerrit
-----BEGIN GEEK CODE BLOCK----- http://www.geekcode.com
Version: 3.12
GCS dpu s-:-- a14 C++++>$ UL++ P--- L+++ E--- W++ N o? K? w--- !O
!M !V PS+ PE? Y? PGP-- t- 5? X? R- tv- b+(++) DI D+ G++ !e !r !y
-----END GEEK CODE BLOCK----- moc.edockeeg.www//:ptth




More information about the Python-list mailing list