tags:

views:

214

answers:

6

I have a text file looks like:

first line  
second line  
third line  
forth line  
fifth line  
sixth line

I want to replace the third and forth lines with three new lines. The above contents would become:

first line  
second line  
new line1  
new line2  
new line3    
fifth line  
sixth line

How can I do this using Python?

+1  A: 

Open a second file to write to, read and then write the lines you want to copy over, write the new lines, read the lines you want to skip, then copy the rest.

Ignacio Vazquez-Abrams
This is ideal, as (unlike several other suggestions) it doesn't require reading the entire file (size unspecified) into memory.
Charles Duffy
@Charles Duffy, Mark Tolonen's solution is the only on I see here that reads the while file into memory at once
gnibbler
Size was specified..."I have a text file [that] looks like:" :^)
Mark Tolonen
@Mark: OP is a "repeat offender". Who knows *how* large the file actually is...
Ignacio Vazquez-Abrams
@gnibbler - anurag's did as well, and the top-rated answer at the time when my comment was written presented an all-in-memory solution as the first of its two proposed solutions.
Charles Duffy
A: 

Read the whole file as a list of lines, then replace the lines you want to delete with a new list of lines:

f = open('file.txt')
data = f.readlines()
f.close()
data[2:4] = [
    'new line1\n',
    'new line2\n',
    'new line3\n']
f = open('processed.txt','w')
f.writelines(data)
f.close()

Note that list slicing is zero-based, and [2:4] means "element 2 up to but not including element 4".

Mark Tolonen
A: 

There are be several ways to achieve that

  1. if you file is small and your lines unique, you can just read whole file and replace the line e.g.

    f.read().replace("third line", "new line1\nnew line2\nnew line3")

  2. But if the file is big or lines not unqiue, just read thru file line by line, and output each line but at third line output three different lines

e.g

for i, line in enumerate(f):
    if i == 2:
        o.write(myThreelines)
    else:
        o.write(line)
Anurag Uniyal
+1  A: 

For python2.6

with open("file1") as infile:
    with open("file2","w") as outfile:
        for i,line in enumerate(infile):
            if i==2:
                # 3rd line
                outfile.write("new line1\n")
                outfile.write("new line2\n")
                outfile.write("new line3\n")
            elif i==3:
                # 4th line
                pass
            else:
                outfile.write(line)

For python3.1

with open("file1") as infile, open("file2","w") as outfile:
    for i,line in enumerate(infile):
        if i==2:
            # 3rd line
            outfile.write("new line1\n")
            outfile.write("new line2\n")
            outfile.write("new line3\n")
        elif i==3:
            # 4th line
            pass
        else:
            outfile.write(line)
gnibbler
+2  A: 
import os
i = open(inputFilePath, 'r')
o = open(inputFilePath+"New", 'w')

lineNo = 0
for line in input:
    lineNo += 1
    if lineNo != 3:
        o.write(line)
    else:
        o.write(myNewLines)

i.close()
o.close()
os.remove(inputFilePath)
os.rename(inputFilePath+"New", inputFilePath)

Hope this helps

inspectorG4dget
There's no need to maintain your own counter with `enumerate()` available.
Ignacio Vazquez-Abrams
+3  A: 
import fileinput
myinsert="""new line1\nnew line2\nnew line3"""
for line in fileinput.input("file",inplace=1):
    linenum=fileinput.lineno()
    if linenum==1 or linenum>4 : 
        line=line.rstrip()
    if linenum==2:
        line=line+myinsert
    print line

Or if you file is not too big,

import os
myinsert=["new line3\n","new line2\n","new line1\n"]
data=open("file").readlines()
data[2:4]=""
for i in myinsert:data.insert(2,i)
open("outfile","w").write(''.join(data))
os.rename("outfile","file)
ghostdog74