faqts : Computers : Programming : Languages : Python : Snippets

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

1 of 1 people (100%) answered Yes

Entry

Merge / Reading from file / Assignment expression

Jul 5th, 2000 10:01
Nathan Wallace, Hans Nowak, Snippet 222, Michael P. Reilly


"""
Packages: files
"""
"""
: ['solve away' assignment in conditionals by fixing type/class split] :>
(Was it Paul Prescod who asked for the appropriately general solution :>
to this problem? I think "we could eliminate the need for assignment :> in
conditionals if we could subclass from C types" is probably the :> biggest
suggested so far....)
: I think that was me, in response to Paul Prescod. :)
: By the way, doesn't there already exist a file reading class that does :
lazy evaluation? I'm starting to feel more and more for a solution :
involving a clear use of lazy evaluation; and subclassing from Python :
types would surely help. Especially since foo; bar; baz aka :
'supertuples' are starting to sound scarier all the time.
It doesn't seem to be what ppl want, but fileinput.input creates an
instance of the fileinput.FileInput class.
"""
# a little merge program
import fileinput
a = fileinput.FileInput('file1')
b = fileinput.FileInput('file2')
i = 0
while 1:
  try:   line1 = a[i]
  except IndexError: line1 = ''
  try:   line2 = b[i]
  except IndexError: line2 = ''
  if line1 and line2:
    sys.stdout.write(line1)
    sys.stdout.write(line2)
  elif line1:
    sys.stdout.write(line2)
  elif line2:
    sys.stdout.write(line1)
  else:
    break
  i = i + 1 # note that __getitem__ checks the value of "i"
a.close()
b.close()
"""
It was suggested _many_ times (by myself once) that the FileInput class be
used for this one idiom.. but ppl wanted to corrupt one of Python's early
philosophies: no assignment in expressions.  Python has been described as
a "language very much like pseudocode" to praise its clear, clean syntax
and idioms.  But then some people think C and Perl have clear, clean
syntax.
"""