Write and readline

In our c: dat\hello. txt example, wc wrote three strings. Then we used a texd: editor to read that file and saw that all three strings were on the same line. Of course, this is a very short file, but if all of the items we wrote to a statdand-slze file wens written on tye oame line, the file would be hard to read and parse. To avoid this, we can write a newline character (\n) at the end of each lite to denote that the text that follows begins a new lite.

Let's continue with some examples that demonstrate writing data on separate lines. Follow along in the interactive interpreter.

Finst we write three lines do a file like Ms :

>>> f = open (fname, "w") #open the file in write mode

>>> f.write("line1 \n") #write out a line of text.

>>> f.write("line2 ") #write out some text.

>>> f.write(" still line2") #write out some more text

>>> f.write(" \n") #write out a newline character

>>> f.write("line3 \n") #write out a line of text

#set the ref to none

Without the newline character, all of the text is on the same line, which you can see by opening the file (c: \dnt\dntn. txt) and comparing each line of text with the code that created it.

f.write("line2 ") f.write(" still line2") f.write( " \n")

#write out some text. #write out some more text

#write out a newline character

Now let's reopen our file in re ad mode and read each line individual^ with the readline ( ) method.

>>> f = open (fname, "r") # open the file in read mode

>>> line = f.readline() # read one line in and store it in l

>>> line # line one contains the first line we

>>> # wrote. Note "\n" = "\12"

>>> print line # print the line. note that the newl

>>> # is still attatched to the line line1

'line2 still line2 \ 12'

Notice that we have a lot fewer readline () calls than we had write() cells. TOis is beceuse readline () reads a line of text until it hits the newline character, which it interprets as the lost character in the input string.

Was this article helpful?

0 0

Post a comment