Moving from perl to python: questions
Remco Gerlich
scarblac-spamtrap at pino.selwerd.nl
Wed Feb 16 10:20:53 EST 2000
David R. Favor wrote in comp.lang.python:
> #!/usr/local/bin/python
>
> def slurp(filename):
>
> "Slurp all the lines of a file into an array"
>
> print filename
>
> try:
> f = open(filename)
>
> lines = f.readlines()
>
> f.close()
>
> return lines
You use try:, but you don't catch any exceptions the open may raise.
With error checking, that could look like:
import sys
def slurp(filename):
"Slurp all the lines of a file into an array"
print filename
try:
f = open(filename)
except IOError:
print "IOError: ", sys.exc_value
return None
return f.readlines()
> def chomp(lines):
> "remove the end of line markers from array"
> import os
> nl_len = len(os.linesep) # length of os dependent line seperator
> while i < len(lines):
> line_len = len(lines[i])
> lines[i] = lines[i][:line_len-nl_len]
Your while has an error; you never change i.
I'm quite sure that the length of the OS dependent line seperator
is irrelevant - unless you opened the file as binary, Python has
already translated it for you, and it's just '\n' now.
Also, instead of 'line_len-nl_len' you can just use '-nl_len'; negative
numbers count from the end, because this is such a typical case.
So line = line[:-1] cuts the \n off (well, any last character).
Also, I think making such a chomp function that takes an array is
not the right way - rather make a function that chomps one string, and
then iterate over it.
But the array version goes something like:
def chomp(lines):
"Remove the end of line markers from an array of strings"
for i in range(len(lines)):
if lines[i][-1] == '\n':
lines[i] = lines[i][:-1]
But there have been other solutions posted here last week; a thread
on 'chomp' came up.
> if __name__ == '__main__':
>
> from sys import argv
> #from getopt import *
>
> #opts = getopt(sys.argv[:1],'f:')
>
> lines = slurp(str(argv[1:]))
>
> print lines
Oh wait, you're writing cat :).
Still not sure what you want to do with argv[1:]. You could join them
(import string; string.join(argv[1:])) but that gives a string like
"foo bar" if you call it with two files.
What about just:
if __name__ == '__main__':
import sys
for file in sys.argv[1:]:
lines = slurp(file)
if lines:
chomp(lines)
for line in lines:
print line
Instead of chomping the lines before printing them, you can also just
send them to sys.stdout, which doesn't add a newline.
Success - this language is quite different from Perl, try not to
write Perl in Python :)
--
Remco Gerlich, scarblac at pino.selwerd.nl
'Oook?'
More information about the Python-list
mailing list