从一个文件读取并在Python中写入另一个文件

时间:2015-03-11 20:51:13

标签: python

我正在编写一个程序,该程序在文件中找到某些文本行,并将它们写入另一个文件,以消除其间的所有烦人文本(它是.vmg文件)。通过我的python和googleing技巧,我编写了以下程序。

with open("filein.txt") as f:
    with open("fileout.txt", "w") as f1:
        for line in f:
            if "telephone number" in line:
                f1.write(line)
            if "telephone number" and "X-BOX" in line:
                f1.write(line)
            if "Subject" in line:
                f1.write(line)

该计划工作正常,但对于"主题"我想告诉程序不仅要编写关键字" subject"的单行文本。是,但直到它达到某个关键字(在我的情况下是" END:VBODY")。我该怎么办?

4 个答案:

答案 0 :(得分:0)

不是最优雅的,但您可以使用一个标志来指示光标是否位于Subject和END之间:VBODY ::

with open("filein.txt") as f:
    with open("fileout.txt", "w") as f1:
        for line in f:
            if in_subject:
                f1.write(line)
                if "END:VBODY" in line:
                    in_subject = False
            else:
                if "telephone number" in line:
                    f1.write(line)
                if "telephone number" and "X-BOX" in line:
                    f1.write(line)
                if "Subject" in line:
                    in_subject = True
                    f1.write(line)

答案 1 :(得分:0)

如果您只需要这个特例,您可以使用简单的状态变量离开。像这样:

inside_subject = False
with open("fileout.txt", "w") as out:
    for line in open("filein.txt", "r"):
        if inside_subject:
            if not "END:VBODY" in line:
                print line
            else:
                inside_subject = False
        else:
            if "telephone number" in line:
                out.write(line)
            elif "telephone number" in line and "X-BOX" in line: # will never match this though
                out.write(line)
            elif "Subject" in line:
                out.write(line)
                inside_subject = True

虽然如果您有更多条件,请考虑使用某个状态机。

答案 2 :(得分:0)

if "Subject" in line:
    f1.write(line[:line.index("END:VBODY")])

答案 3 :(得分:0)

这是另一种工作解决方案,只需在if "Subject" in line条件下添加while循环。

with open("filein.txt") as f:
    with open("fileout.txt", "w") as f1:
        for line in f:
            if "telephone number" in line:
                f1.write(line)
            if "telephone number" and "X-BOX" in line:
                f1.write(line)
            if "Subject" in line:
                f1.write(line)

                # new code added here
                while 'END:VBODY' not in line:
                    line = f.next()
                    f1.write(line)