Python—为单个文件的每个部分编写单独的文件

Python—为单个文件的每个部分编写单独的文件,python,python-2.7,parsing,Python,Python 2.7,Parsing,我有一个包含5段数据的.txt文件。每个部分都有一个标题行“section X”。我想从这个单独的文件中解析并编写5个单独的文件。该节将从标题开始,在下一节标题之前结束。下面的代码创建5个单独的文件;然而,它们都是空白的 from itertools import cycle filename = raw_input("Which file?: \n") dimensionsList = ["Section 1", "Section 2", "Section 3", "Section

我有一个包含5段数据的.txt文件。每个部分都有一个标题行“section X”。我想从这个单独的文件中解析并编写5个单独的文件。该节将从标题开始,在下一节标题之前结束。下面的代码创建5个单独的文件;然而,它们都是空白的

from itertools import cycle

filename = raw_input("Which file?: \n")

dimensionsList = ["Section 1", "Section 2",
    "Section 3", "Section 4", "Section 5"]

with open(filename+".txt", "rb") as oldfile:
    for i in dimensionsList:
        licycle = cycle(dimensionsList)
        nextelem = licycle.next()
        with open(i+".txt", "w") as newfile: 
            for line in oldfile:
                if line.strip() == i:
                    break
            for line in oldfile:
                if line.strip() == nextelem:
                    break
                newfile.write(line)
问题 测试代码时,它只对第1部分有效(其他部分对我来说也是空白)。我意识到问题在于各部分之间的转换(还有,
licycle
在所有部分重新启动)

第2节在的第二个
处读取(
如果line.strip()==nextem
)。下一行是第2节的数据(而不是第2节的文本)

这很难用文字表达,但请测试以下代码:

from itertools import cycle

filename = raw_input("Which file?: \n")

dimensionsList = ["Section 1", "Section 2", "Section 3", "Section 4",
                  "Section 5"]

with open(filename + ".txt", "rb") as oldfile:
    licycle = cycle(dimensionsList)
    nextelem = licycle.next()
    for i in dimensionsList:
        print(nextelem)
        with open(i + ".txt", "w") as newfile:
            for line in oldfile:
                print("ignoring %s" % (line.strip()))
                if line.strip() == i:
                    nextelem = licycle.next()
                    break
            for line in oldfile:
                if line.strip() == nextelem:
                    # nextelem = licycle.next()
                    print("ignoring %s" % (line.strip()))
                    break
                print("printing %s" % (line.strip()))
                newfile.write(line)
            print('')
它将打印:

Section 1
ignoring Section 1
printing aaaa
printing bbbb
ignoring Section 2

Section 2
ignoring ccc
ignoring ddd
ignoring Section 3
ignoring eee
ignoring fff
ignoring Section 4
ignoring ggg
ignoring hhh
ignoring Section 5
ignoring iii
ignoring jjj

Section 2

Section 2

Section 2
它为第1节工作,它检测第2节,但它一直忽略这些行,因为它没有找到“第2节”

如果每次重新启动这些行(总是从第1行开始),我认为程序会工作。但是我做了一个更简单的代码,应该适合你

解决方案 如果找到该节,它将开始在这个新文件中写入。否则,请继续在此当前文件中写入

Ps.:下面是我使用的文件示例:

Section 1
aaaa
bbbb
Section 2
ccc
ddd
Section 3
eee
fff
Section 4
ggg
hhh
Section 5
iii
jjj
Section 1
aaaa
bbbb
Section 2
ccc
ddd
Section 3
eee
fff
Section 4
ggg
hhh
Section 5
iii
jjj