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 开发者_JS百科 fifth line sixth line
How can I do this using Python?
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)
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)
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".
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.
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
There are be several ways to achieve that
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")
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)
精彩评论