在Python中将文件分割成带有关键字的文件?

drb*_*sen 3 python python-3.x

我试图弄清楚如何使用关键字作为分割指示器来获取文件并分成子文件。就我而言,我有一个如下所示的大文件:

Racecar
line2...
line3...
Racecar
line5...
line6...
line7...
line8...
Racecar
line10...

每次出现该词时,Racecar我都想拆分文件并创建一个子文件。使用上面的示例,File_1 将有 3 行,File_2 将有 5 行,File_3 将有 2 行。这些文件看起来像这样:

文件_1:
Racecar
line2...
line3...

文件_2:
Racecar
line5...
line6...
line7...
line8...

文件_3:
Racecar
line10...

我意识到 sed 或 awk 之类的东西更适合于此,但我需要在 Python 中执行此操作。由于某种原因我真的被困在这个问题上了。我尝试写这样的东西:

with open("bigfile", mode="r") as bigfile:
    reader = bigfile.readlines()
    for i,line in enumerate(reader):
        if line.startswith("Racecar"):
            header = line
            header_num = i
Run Code Online (Sandbox Code Playgroud)

我似乎陷入了困境,因为我找不到找到下一次出现 Racecar 的方法。我一直想使用该next()函数,但显然这不适用于字符串。我正在使用的文件足够小,可以读入内存。谁能帮我这个?提前致谢。

Vad*_*der 5

with open("bigfile", mode="r") as bigfile:
    reader = bigfile.read()
    for i,part in enumerate(reader.split("Racecar")):
        with open("File_" + i+1, mode="w") as newfile:
            newfile.write("Racecar"+part)
Run Code Online (Sandbox Code Playgroud)