我的文本文件如下:
first line second line third line forth line fifth line sixth line
我想用三个新行替换第三行和第四行。以上内容将成为:
first line second line new line1 new line2 new line3 fifth line sixth line
如何使用Python执行此操作?
答案 0 :(得分:7)
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)
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)
答案 1 :(得分:4)
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
或者如果你的文件不是太大,
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)
答案 2 :(得分:3)
将整个文件作为行列表读取,然后用新的行列表替换要删除的行:
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()
请注意,列表切片是从零开始的,[2:4]表示“元素2最多但不包括元素4”。
答案 3 :(得分:2)
打开第二个文件,写入,读取然后写下要复制的行,写新行,读取要跳过的行,然后复制其余行。
答案 4 :(得分:1)
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)
希望这有帮助
答案 5 :(得分:0)
有几种方法可以实现这个目标
如果您的文件很小并且您的行是唯一的,您可以只读取整个文件并替换该行,例如
f.read()。replace(“第三行”,“new line1 \ nnew line2 \ nnew line3”)
但是如果文件很大或行不是unqiue,只需逐行读取文件,并输出每一行但在第三行输出三行不同
e.g
for i, line in enumerate(f):
if i == 2:
o.write(myThreelines)
else:
o.write(line)