python - 除了特定的文本块外,如何将行写入新文件?
问题描述
我正在打开一个文本文件,搜索特定行(将前几行写入新文件)。找到该行(“BASE CASE”)后,我想搜索特定的文本块以从文件中删除。
我通过在线研究类似问题构建了一些代码。现在,它只创建一个空的新 eve 文件。当我尝试删除空白文件时,它还给我一个错误“这个文件正在 python 中使用”。旧文件的示例如下:每个块可能有未知数量的监视器。
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
我目前拥有的代码是:
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()
我希望将旧的 txt 文件重新打印到新文件,同时删除第一个“End”和“Monitor 1”之间的文本块。当前的问题包括输出文件为空白以及输出文件在 python 中保持打开状态。
解决方案
您正在描述一个简单的状态机。你的状态是:
- 初始状态——将行写入新文件
- 找到“BASE CASE”——将行写入新文件
- 找到“结束”——什么都不做
- 这一行是“监视器 1”——将行写入新文件
- 稍后,到 EOF - 将行写入新文件
因为只有两个动作(“写”和“不写”),你可以用一个状态变量和一个动作标志来处理它。像这样的东西:
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)
如果你愿意,你可以把它写成一系列隐式状态循环:
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()
...
你能从那里拿走吗?
推荐阅读
- c# - 使用 HttpWebRequests 获取 Json 数据
- c# - 泛型类还是泛型方法?哪个是好习惯?
- reactjs - 为什么可视化有延迟?
- python - 如何使用rest API使用social-auth-app-django库断开社交身份验证与django的连接
- algorithm - 用于非刚性点云对齐的凸混合整数
- opencv - cv2.error:OpenCV(4.3.0)../opencv_contrib/modules/dnn_superres/src/dnn_superres.cpp:97:错误:(-2:未指定的错误)模型未指定
- python - 连接到 0.0.0.0 上的测试 SFTP 服务器
- c++ - 围绕强制省略复制/移动的令人困惑的行为
- vue.js - Vue index.html 包含几个延迟加载组件的标签
- reactjs - 如何跳转到vscode中第一个组件的引用?