python - 如何检查是否在txt文件中的某个点之前找到了某行?
问题描述
我需要弄清楚在文本文件中出现另一个短语之前是否找到了某个短语/行。如果找到该短语,我将通过,如果它不存在,我将在截止点上方添加一行。值得注意的是,该短语也可能出现在文档的后面。
这种 txt 格式的示例可能是:
woijwoi
woeioasd
woaije
Is this found
owijefoiawjwfioj
This is the cutoff
asoi w
more text lines
Is this found
aoiw
搜索应该在“This is the cutoff”这个短语上截断。不知道截止将在哪条线上。如果在截止之前存在“Is this found”,则通过。如果没有,我想在输出文档的截止点上方添加短语“添加一行”。到目前为止我尝试过的代码示例,之前定义了所有字符串:
find = 'Is this found'
with open(longStr1) as old_file:
lines = old_file.readlines()
with open(endfile1, "w") as new_file:
for num, line in enumerate(lines):
if "This is the" in line:
base_num = num
for num in range(1, base_num):
if not find in line:
if line.startswith("This is the"):
line = newbasecase + line
我收到“未定义名称'base_num'”的错误是否有更好的方法来执行此搜索?
解决方案
这样的事情呢?查找查找和截止索引位置,然后循环遍历行列表并检查截止索引,评估是否存在先前的“查找”变量,如果没有则添加“添加行”行并结束新文件。
find = "Is this found"
find_index = 0
cutoff = "This is the cutoff"
cutoff_index = 0
with open(longStr1) as old_file:
lines = old_file.readlines()
if find in lines:
find_index = lines.index(find)
if cutoff in lines:
cutoff_index = lines.index(cutoff)
with open(endfile1, "w") as new_file:
for num, line in enumerate(lines):
if cutoff in line:
if cutoff_index < find_index:
new_file.write("Adding a line\n")
new_file.write(line)
break
new_file.write(line)
推荐阅读
- bash - 在 100+MB SQL 转储中插入三个块(SQL 行)
- extjs - ExtJS:如何使 tabreorderer 插件选项卡定位有状态
- c - STM32 CAN 通信 Rx 期间接收随机数据字节
- apache - 无法解决 htaccess 重写问题(对 seo 友好的 URL)
- ios - 如何确保字典中的所有键都已初始化
- haskell - 结合来自两个 Either Monad 的结果
- reactjs - 当我使用 Metro bundle 运行和测试应用程序时,它运行良好。但是当我构建 android apk 它无法正常工作时,它会再次重新启动
- django - FilterView、get_context_data() 不起作用。没有属性“object_list”,但有一个
- python - 用python在sql字段中添加+10
- docker - docker 容器内的 Gunicorn 不断为 Flask 应用程序启动工作程序(容器部署在 VMWARE ESXi 上的 CentOS/Ubuntu 客户机上)