Python File Reading and Writing

Posted on 2005-05-13
Last Modified: 2012-06-27
This is a small program i have written to read a contents from a INPUT FILE containing (+1000 Lines ) and writing simultaneously to another file. ( it works fine )

1.---- QUESTION:-
I need to have the same fomat for the written file as of the Reading file ( But the FORMAT is LOST ------ I Dont Know why ?????
if want to make a stop at the middle of the file and insert some data to the file and then again  perfrom the read  and the write operation( HOW CAN I DO THAT)........

import sys
import os
import stat

def ReadFile():
            input = open('c:\Abafiles\Job-1.inp','r')
            out = open("exampleWrite.inp", "w")
            s = input.readlines()
            InputTuple = []
            for line in s:
                  singleLine = line.rstrip()
            print len(InputTuple)
      except IOError, (errno, strerror):
            print "I/O error(%s): %s" % (errno, strerror)
      except ValueError:
            print "Could not convert data to an integer."
            print "Unexpected error:", sys.exc_info()[0]
Question by:ashok3sep
    LVL 15

    Accepted Solution

    1.  The line

    singleLine = line.rstrip()

    removes the newline character at the end of each input line.  If you want to keep those characters, don't call that function.

    2.  The program does not simultaneously read and write.  It reads the whole file in at once (input.readlines()), then writes it out one line at a time (out.write(singleLine)).  So if you want to insert some data, you can write out some of the input lines, write out some inserted lines, then write out the rest of the input lines.

    For example, to insert a line between the fifth and sixth lines of the input:

    for line in s[:5]

    out.write("inserted line\n")

    for line in s[5:]
    LVL 5

    Author Comment

    But i dont know the line number before

    I need to check for the file for some data.

    for example i have a text file "hallo.txt"

    1    11    21
    2    12    22
    3    13    23
    4    14    24
    5    15    25
    6    16    26
    7    17    27
    8    18    28

    Now i need to insert a line 2002    12    22 in the third line and my new file should look like this

    1    11    21
    2    12    22
    2002   12    22
    3    13    23
    4    14    24
    5    15    25
    6    16    26
    7    17    27
    8    18    28

    sometimes i need to insert 3003   13    33 after 3rd line and so on........
    so i need to check each and every line and then if i find a match then i need to insert a line next to it

    how can i find the desired line number from the file and then i need to insert some data to the file and then do the read operation.

    LVL 15

    Expert Comment

    You don't need to know the line number.  You can just read the lines one by one and examine them, and decide for each one whether to insert something after it.

    For example:

    for line in s:
      if INeedToInsertALineAfterThis(line):

    Here INeedToInsertALineAfterThis and LineToInsertAfter are functions you would have to write.  Of course, you don't have to use functions.  If the logic is simple enough, you can just stick it in where I have the function calls.

    LVL 9

    Assisted Solution

    You can also try something like this (if you really want to read one line at a time and then write the output):

    for line in file( infile, 'r' ):
        if INeedToInsertALineBeforeThis( line ):
            outfile.write( LineToInsertBeforeThis( line ) )
        outfile.write( line )
        if INeedToInsertALineAfterThis( line ):
            outfile.write( LineToInsertAfterThis( line ) )

    Needless to say, this is just a minor modification of efn's answer. Note that line holds the entire line, including new line characters.
    LVL 28

    Expert Comment

    The rule of thumb: Never use backlashes in paths in Python. You will do less mistakes when forgetting to double the backslash in strings (like in the question).

    Featured Post

    Highfive Gives IT Their Time Back

    Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

    Join & Write a Comment

    This article will show the steps for installing Python on Ubuntu Operating System. I have created a virtual machine with Ubuntu Operating system 8.10 and this installing process also works with upgraded version of Ubuntu OS. For installing Py…
    When we want to run, execute or repeat a statement multiple times, a loop is necessary. This article covers the two types of loops in Python: the while loop and the for loop.
    Learn the basics of strings in Python: declaration, operations, indices, and slicing. Strings are declared with quotations; for example: s = "string": Strings are immutable.: Strings may be concatenated or multiplied using the addition and multiplic…
    Learn the basics of lists in Python. Lists, as their name suggests, are a means for ordering and storing values. : Lists are declared using brackets; for example: t = [1, 2, 3]: Lists may contain a mix of data types; for example: t = ['string', 1, T…

    755 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    19 Experts available now in Live!

    Get 1:1 Help Now