简体   繁体   English

除了特定的文本块,如何将行写入新文件?

[英]How to write lines to a new file except for a specific block of text?

I am opening a text file, searching to find a specific line(writing previous lines to a new file). 我正在打开一个文本文件,搜索以查找特定行(将以前的行写入新文件)。 Once that line ("BASE CASE") is found, I want to search for a specific block of text to delete form a file. 找到该行(“ BASE CASE”)后,我要搜索特定的文本块以从文件中删除。

I have constructed some code through researching similar problems online. 我通过在线研究类似问题构建了一些代码。 Right now, it only creates an empty new eve file. 现在,它仅创建一个空的新eve文件。 It also gives me an error that "this file is being used in python" when I try to delete the blank files. 当我尝试删除空白文件时,这也给我一个错误:“此文件正在python中使用”。 An example of what the old file looks like would be this: There can be an unknown number of monitors for each block. 旧文件的示例如下:每个块可能有未知数量的监视器。

xxxoijasdf
Monitor 4
aowijefoi
BASE CASE

Monitor 5
Monitor 3
Monitor 2
Item 1 Item 2
End

Monitor 3
Monitor 4
Item 3 Item 4
End

Monitor 1
Item 5 Item 6
End

The code I currently have is: 我目前拥有的代码是:

    longStr1 = (r"C:\Users\jrwaller\Documents\Automated Eve\NewTest.txt")
    endfile1 = (r"C:\Users\jrwaller\Documents\Automated Eve\did we do it yet.txt")

    search_item = "Item 3 Item 4"

    with open(longStr1, "r") as f:
        with open(endfile1, "w") as new_file:
            lines = f.readlines()
            i=0
            while i < 2000:
                for line in f:
                    if lines[i] != 'BASE CASE':
                        new_file.write(lines[i])
                    else:
                        new_file.write(lines[i])
                        newfile.write(lines[i+1])
                        block = ''
                        for line in f:
                            if block:
                                block += line
                                if line.strip() == 'End':
                                    if search_item not in block: new_file.write(block + '\n')
                                    block = ''
                            elif line.startswith('Monitor'):
                                block = line
        new_file.close()
    f.close()

I am hoping to reprint the old txt file to the new file while deleting the block of text between the first 'End' and 'Monitor 1'. 我希望将旧的txt文件重新打印到新文件,同时删除第一个“ End”和“ Monitor 1”之间的文本块。 Current problems include the output file being blank and the output file being left open in python. 当前的问题包括输出文件为空白,而输出文件在python中保持打开状态。

You are describing a simple state machine. 您正在描述一个简单的状态机。 Your states are: 您的状态是:

  1. initial state -- write lines to new file 初始状态-将行写入新文件
  2. found "BASE CASE" -- write lines to new file 找到“ BASE CASE”-将行写入新文件
  3. found "End" -- do nothing 发现“结束”-无所事事
  4. this line is "Monitor 1" -- write lines to new file 该行是“监视器1”-将行写入新文件
  5. later, to EOF -- write lines to new file 稍后到EOF-将行写入新文件

Since there are only two actions ("write" and "don't write"), you can handle this with a state variable and an action flag. 由于只有两个动作(“写”和“不写”),您可以使用状态变量和一个动作标志来处理它。 Something like this: 像这样:

state = 1
write_out = True
for line in f:
    # Looking for "BASE CASE"; write line until then
    if state == 1:
        if "BASE CASE" in line:
            state = 2

    # Look for start of unwanted block
    elif state == 2:
        if "End" in line:
            state = 3
            write_out = False

    # Look for end of unwanted block
        ...

    # Acknowledge moving past "Monitor 1"
        ...

    # Iterate through rest of file
        ...

    if write_out:
        new_file.write(line)

If you prefer, you can write this as a sequence of implicit-state loops: 如果愿意,可以将其编写为一系列隐式状态循环:

while not "BASE CASE" in line:
    new_file.write(line)
    line = f.readline()

while not "End" in line:
    new_file.write(line)
    line = f.readline()

while not "Monitor 1" in line:
    # Don't write this block to the output
    line = f.readline()

...

Can you take it from there? 你能从那里拿走吗?

longStr1 = (r"C:\Users\jrwaller\Documents\Automated Eve\NewTest.txt")
endfile1 = (r"C:\Users\jrwaller\Documents\Automated Eve\did we do it yet.txt")

search_item = "Item 3 Item 4"

with open(longStr1, "r") as f:
    with open(endfile1, "w+") as new_file:
        state = 1
        write_out = True
        for line in f:
            if state == 1:
                write_out = True
                if "BASE CASE" in line:
                    state = 2
            elif state == 2:
                if line == '\n':
                    write_out = True
                    state = 3
            elif state == 3:
                write_out = True
                block = ''
                for line in f:
                    if block:
                        block += line
                        if line.strip() == 'End':
                            if search_item not in block: new_file.write(block + '\n')
                            block = ''
                    elif line.startswith('Monitor'):
                        block = line
                if search_item in line:
                    state = 4 
                    write_out = False
            elif state == 4:
                write_out = False
                if "End" in line:
                    state = 5    
                    write_out = False
            elif state == 5:              
                if "Monitor" in line:
                    write_out = True
                    state = 6                  
            elif state == 6:
                write_out = True
            if write_out:
                new_file.write(line)
f.close()
new_file.close()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何将文本的特定行写入新文件? - How to write specific lines of a text to a new file? 如何从文本文件中仅提取具有特定单词的行并编写一个新行? - How to extract only lines with specific word from text file and write a new one? 如何在文本文件中搜索包含特定单词的行,然后使用“找到”行创建一个新文件 - How to search a text file for lines that contain a specific word, then create a new file with the "found" lines CSV文件写入,需要将特定行写入新的csv文件 - CSV file writing, need to write specific lines to new csv file 如何删除文件中除第一个字符外的所有行? - How to remove all lines in a file containing a specific character except for the first? 如何编写 python 从名为“file1.txt”的文本文件中读取前两行 将从“file1.txt”读取的两行写入新文件“file2.txt” - How write python to Read the first two lines from a text file named "file1.txt" Write the two lines read from "file1.txt" to a new file "file2.txt" Python 将一系列数字之间的文本行写入新文件 - Python Write lines of a text in between a range of numbers to a new file Python不会每次将新行写入文本文件 - Python won't write each time new lines into text file 如何在保留旧行的同时在文本文件中写新行 - How can I write on new lines in a text file while preserving old ones 如何从文本文件中删除特定行? - How to remove specific lines from a text file?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM