Reading/writing files

Graham Ashton graham at effectif.com
Mon Apr 14 15:07:37 EDT 2003


On Mon, 14 Apr 2003 18:32:02 +0100, lost wrote:

> Hi there,
> I'm a bit lost in terms of reading and writing files. I've been reading
> the python docs that came with my distibution, and they aren't too
> clear. I need something like this
> 
> for line in a file
> 	print line
> print done

You're very nearly there. I made a file called foo.txt with these lines
in:

shoe
fruit
wheel barrow

Then I wrote a script to print out each line:

    for line in file('foo.txt'):
        print line
    print 'done'

If you run it you'll find you get a blank line between each line in your
input file. That's because print automatically appends a new line
character to the end of each line it prints, and the file already contains
new line characters. To get round that, you could import the sys module
and use sys.stdout.write(line) inplace of the print statement.
Alternatively you could use the rstrip() method on a string (see below).

When you open a file for writing, you need to say that you want to write
to it. Add a second option to the write() method like this:

    output_file = file('bar.txt', 'w')

Improving on the example above, I wrote this:

    input_file = file('foo.txt')
    output_file = file('bar.txt', 'w')
 
    line_num = 0
    for line in input_file:
        line_num += 1
        output_file.write('%d: %s' % (line_num, line))
 
    input_file.close()
    output_file.close()
 
    print 'done'

Note that this example stores each file object in a variable and calls
close() on them both when it's done with them. If you don't close a file
yourself it'll get closed by Python, but it'll happen at a time of
Python's choosing, not yours. It's generally thought to be better practice
to close them yourself.

> Also, do i need to take
> into account the \n at the end of a line? for example, if I have
> hello:there
> and
> hello:there\n
> how could i ignore the \n?

If you have 'hello:there\n' in a variable called line, you can get rid of
the whitespace off the end by calling this:

    line = line.rstrip()

Note that you have to reassign the result of rstrip() to the line
variable, as strings are immutable. There are plenty of other methods that
you can call on strings; read the docs for the string module for more.

Good luck...

--
Graham Ashton




More information about the Python-list mailing list