我想制作一个脚本,执行以下操作:
我有file_ori.txt,它的内容是这样的(数字只是行号而不是实际文本)
1 This is test line with random text
2 This is also a line with lalala text
3 This is that and this and that of a line
4 start sequence
5 This isn't also a line with lalala text
6 This is test line with random text
7 This is also a line with lalala text
8 end sequence
9 This is test line with random text
我要帮忙的是在整个文件中将单词“ line”更改为单词“ Pine”,但只在start sequence
和之间传递新文件中的更改,end sequence
结果是:
1 This is test line with random text
2 This is also a line with lalala text
3 This is that and this and that of a line
4 start sequence
5 This isn't also a Pine with lalala text
6 This is test Pine with random text
7 This is also a Pine with lalala text
8 end sequence
9 This is test line with random text
对于我来说至关重要的是,我不想在替换之前而是在之后才拆分文件。我必须阅读全文。
f = open(file_ori.txt, "r")
full_read = f.read()
full_read = full_read.replace('line', 'Pine')
............. I don't know how to continue
f = open(file_ori_edit.txt, 'w')
f.write(full_read)
f.close()
谢谢。
这是一种方法。
例如:
start = 'start sequence'
end = 'end sequence'
parse = False
result = []
with open(filename) as infile:
for line in infile: #Iterate each line
line = line.strip()
if start == line: #check for start sequence
parse = True
if end == line: #check for end sequence
parse = False
if parse: #Replace ONLY between sequence
line = line.replace('line', 'Pine')
result.append(line+"\n")
with open(filename, "w") as outfile:
outfile.writelines(result)
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句