Delete and insert lines in a text file

I have a text file:

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

I want to replace the third and fourth lines with three new lines. The above content will look like this:

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

How to do it using Python?

+4
source share
6 answers

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) 
+7
source
 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 the file is not too large,

 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) 
+4
source

Read the entire 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 sorting is zero-based, and [2: 4] means "element 2 before, but not including element 4".

+3
source

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

+2
source
 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

+1
source

There are several ways to achieve this.

  • If the file is small and your lines are unique, you can just read the entire file and replace the line, for example.

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

  • But if the file is large or the line is not unqiue, just read through line by line and print each line, but in the third line print three different lines

eg

 for i, line in enumerate(f): if i == 2: o.write(myThreelines) else: o.write(line) 
0
source

Source: https://habr.com/ru/post/1301940/


All Articles