[Tutor] newbie needs simple file handling help

Daniel Yoo dyoo@hkn.eecs.berkeley.edu
Sat, 21 Apr 2001 03:02:07 -0700 (PDT)


On Sat, 21 Apr 2001, N/A wrote:

> Hi, i'm trying to write a program for creating and managing LARP
> character sheets for a friend, I understand most of the basic syntax
> and data handling needed, but I can't figure out how to open and write
> strings to a text file. If it's possible could you send me the
> commands and attributes for this, unfortunatley I don't have the code
> I have written here and my linux box isn't online.

Here's a small program that prints out a multiplication table into the
file "mult.txt":

###
if __name__ == '__main__':
    file = open('mult.txt', 'w')
    for y in range(10, 0, -1):
        for x in range(1, 11):
            file.write( str(x * y) + ' ')
            # Alternatively:  file.write('%s ' % x*y)
        file.write('\n')     
###

The documentation talks about file handling here:

http://python.org/doc/current/lib/bltin-file-objects.html
http://python.org/doc/current/tut/node9.html#SECTION009200000000000000000 

so you can take a look at that for more of the gory details.


By the way, what sort of strings are you trying to write?  Tell us a
little more about how the data's organized, and we can give more helpful
advice.