Printing/writing an integer to a file

Ben Finney bignose+hates-spam at
Fri Nov 17 04:18:12 CET 2006

PS <mytempmailid at> writes:

> Friends,

Please, don't send message bodies to public discussion forums in any
format other than plain text. HTML email in particular has wildly
differing implementations and renderings.

> I am new to python and did search on the web on how to achieve this:
> ( I am trying to append the line numbers to all the lines of a file for now)
> Thanks!!
> =================================================
> import os, sys
> fileName = os.path.join("C:", "temp", "x1.txt")
> fileobject = open(fileName, 'r')
> outputDir = "C://temp//"
> linenumber = 0
> fileName1 = outputDir + " x2.txt"

You've used 'os.path.join' corretly above; you should use that any
time you want to compose a file path.

    output_dir = "C://temp//"
    out_file_name = os.path.join(output_dir, "x2.txt")

> fileobject1 = open(fileName1, 'w')
> while (1):
>     L = fileobject.readline()
>     if L=="":
>         print "**Done"
>         break

A file object is iterable, returning a line of text each time. This
means you don't need to manually loop and extract each line; you can
write this loop as:

    out_file = open(out_file_name, 'w')
    for in_line in in_file:
        # process the line

>     linenumber += 1
>     fileobject1.write (ln)

The function call syntax doesn't allow a space between the function
name and the opening parenthesis.

You are referencing 'ln' without ever defining it. Presumably you mean
to use 'linenumber'.

          linenumber += 1

>     fileobject1.write(":: "+ L)
> fileobject1.close()
> =============================================================

Wrapping all this advice up::

    import os
    import sys

    in_file_name = os.path.join("C:", "temp", "x1.txt")
    in_file = open(in_file_name, 'r')
    out_dir = "C://temp//"
    out_file_name = os.path.join(out_dir, "x2.txt")
    out_file = open(out_file_name, 'w')

    linenumber = 0
    for in_line in in_file:
        linenumber += 1
        out_file.write(":: " + in_line)

    print "**Done"

An improvement would be to use string formatting to construct the
output line:

    linenumber = 0
    for in_line in in_file:
        linenumber += 1
        out_line = "%d:: %s" % (linenumber, in_line)

This also means you're one easy step away from padding the line number
to a minimum width::

        out_line = "%06d:: %s" % (linenumber, in_line)

 \     "I must say that I find television very educational. The minute |
  `\   somebody turns it on, I go to the library and read a book."  -- |
_o__)                                                     Groucho Marx |
Ben Finney

More information about the Python-list mailing list