Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium


Python File Reading and Writing

Posted on 2005-05-13
Medium Priority
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

efn earned 700 total points
ID: 14001536
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:]

Author Comment

ID: 14025336
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

ID: 14027051
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.


Assisted Solution

rjkimble earned 300 total points
ID: 14146986
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 29

Expert Comment

ID: 20019930
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

Receive 1:1 tech help

Solve your biggest tech problems alongside global tech experts with 1:1 help.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

The purpose of this article is to demonstrate how we can upgrade Python from version 2.7.6 to Python 2.7.10 on the Linux Mint operating system. I am using an Oracle Virtual Box where I have installed Linux Mint operating system version 17.2. Once yo…
Article by: Swadhin
Introduction of Lists in Python: There are six built-in types of sequences. Lists and tuples are the most common one. In this article we will see how to use Lists in python and how we can utilize it while doing our own program. In general we can al…
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…
Learn the basics of if, else, and elif statements in Python 2.7. Use "if" statements to test a specified condition.: The structure of an if statement is as follows: (CODE) Use "else" statements to allow the execution of an alternative, if the …
Suggested Courses
Course of the Month11 days, 8 hours left to enroll

564 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