我最近开始使用Python 3,我想知道这里是否有人能帮助我解决以下问题:
假设我有一个类似于以下内容的文件:
Line 0
'Phrase/String that I am looking for'
Line 1
Line 2
Line 3
Line 4
Line 5
Line 6我想做的是
(1)从文本文件末尾开始,搜索特定的phrase/string,
(2)找到字符串后,我想复制第3-5行。
(3)将另一个文件中的第9-11行替换为我最初文本文件中的第3-5行。
到目前为止,我只能找到我的字符串,但我似乎不知道如何执行步骤2和步骤3。
with open("myfile.txt", 'r') as searchfile:
for line in reversed(list(searchfile)):
if 'my string' in line:
print(line)
searchfile.close()同样,我也尝试了一些其他的东西,但是我的脚本直到现在才起作用。所以,我只包括这个。
发布于 2015-05-26 19:53:00
不确定从末尾检查是必要的还是合乎逻辑的,所以如果我们找到行并使用孤岛取我们想要的行,那么只需迭代文件内容中断,然后使用枚举和fileinput.input与inplace=True一起修改另一个文件,在适当的位置添加新的行:
from itertools import islice
from fileinput import input as inp
import sys
with open("in.txt") as f:
sli = None
for line in f:
if line.rstrip() == 'Phrase/String that I am looking for':
f.seek(0) # reset pointer
sli = islice(f, 2, 5) # get lines 3-5, o based indexing
break
if sli is not None:
for ind, line in enumerate(inp("other.txt",inplace=True)):
if ind in {8,9,10}: # if current line is line 9 10 or 11 write the next line from sli
sys.stdout.write(next(sli))
else: # else just write the other lines
sys.stdout.write(line)other.txt:
1
2
3
4
5
6
7
8
9
10
11
12之后:
1
2
3
4
5
6
7
8
Line 1
Line 2
Line 3
12发布于 2015-05-26 19:26:39
这将使您获得第1和第2部分中的3行。
# (?m)[\S\s]*((?:^.*\r?\n){3})^.*phrase
(?m) # Multi-line modifier
[\S\s]* # Greedy, grab all up to ->
( # (1 start)
(?: # Only 3 lines of unknown text
^ .* \r? \n
){3}
) # (1 end)
^ .* phrase # Nex line contains phrasehttps://stackoverflow.com/questions/30467012
复制相似问题