iterating over lines in a file

Donn Cave donn at oz.net
Sat Jul 22 11:54:05 EDT 2000


Quoth nobody <no at bo.dy>:
| cjc26 at nospam.cornell.edu (Cliff Crawford), in
| <slrn8nhj0s.jr0.cjc26 at synecdoche.sowrong.org>:
| > * nobody <no at bo.dy> menulis:
|>> now, this newbie has run into another perl idiom he'd like to figure
|>> out how to rewrite in python - "while (<FILE>) { print; }" - and, by
|>> extension, how to get python to print the string i hand it, the whole
|>> string i hand it, and nothing but the string i hand it?
|
|> Hmm..not quite sure what you mean..maybe you want to use
|> sys.stdout.write() instead?
|
| perhaps. unfortunately, i haven't had time to work on this since i made
| that posting, so i have got no further; i expect there's some fairly easy
...

He's right.  Go ahead and get to work on your program, and use
sys.stdout.write().  Read up on the file object in general, for
more details.

|> print doesn't really try to be clever with its arguments, except for
|> printing a space between each one and a newline at the end.
|
| that's trying to be clever. then, if i'm reading raw lines from a file and
| want to print them verbatim, i have to strip a newline somewhere somehow?
| how do i copy a file to another one, is there a file.copy method in some
| module somewhere?

Not to my knowledge, but you don't need it.  To read, I reckon you're
probably using the file object read() or readline() functions.  The
file object write() function is the inverse operation and doesn't
strip anything.  (Well, note that on some platforms the underlying
C library functions may tamper with the output and input data to
get the CR/LF issues right, so open as binary if that's an issue.)
The "print" statement is not for applications like this.

The os module also exports the POSIX 1003.1 open(), read() and write()
functions, which in a few exotic situations may be more practical than
a file object.

	Donn Cave, donn at oz.net



More information about the Python-list mailing list