python-3.x - 程序不会停止遍历列表
问题描述
def gameinfo():
lines = []
html_doc = 'STATIC.html'
soup = BeautifulSoup(open(html_doc), 'html.parser')
for mytable in soup.find_all('table'):
for trs in mytable.find_all('tr'):
tds = trs.find_all('td')
row1 = [elem.text.strip() for elem in tds]
row = str(row1)
sausage = False
with open("FIRE.txt", "r+") as file:
for line in file:
if row+"\n" in line:
break
else:
if row.split(",")[:4] == line.split(",")[:4]:
print(row)
print(line)
file.write(line.replace(line+"\n", row+"\n"))
print('Already exists with diff date')
sausage = True
break
if sausage == False:
print(row.split(",")[:4])
print(line.split(",")[:4])
print(row)
print(line)
file.write(row+"\n")
print('appended')
while True:
gameinfo()
gameinfo()
该程序应该继续在文本文件中搜索FIRE.txt
与变量匹配的行row
。当我运行它时,它工作正常,但是应该检查列表的前四个元素是否相同的代码部分,然后皮肤下面的附加部分,不起作用。当程序检测到字符串的前 4 个元素变成了与文本文件中另一个字符串的前 4 个元素匹配的列表(行)时,它应该覆盖文本文件中的字符串。但是,当它检测到具有相同前 4 个元素的列表时,它会永远循环并且永远不会中断。
我的字符串如下所示: ['Infield Upper Deck Reserved 529', '$17.29', '4', '2', '175'] 我将其与如下列表进行比较: ['Infield Upper Deck Reserved 529 ', '$17.29', '4', '2', '170'] 并且当它看到列表中的前 4 个元素相同时,它应该覆盖文本文件中开始的那个,但是它正在循环。
解决方案
问题变了;最新版本最后。
我认为您想使用该csv
模块。如果您直接遍历一个csv.reader
对象而不是文件对象,您将获得每一行作为一个列表。
例子:
import csv
row = ["this", "is", "an", "example"]
with open("FIRE.txt", "r+") as file:
reader = csv.reader(file)
for line in reader:
if row in line:
break
pass
或者,如果您不需要在 Python 以外的任何东西中使用它,您可以pickle
使用collections.OrderedDict
前四个项目的元组作为键:
import collections
import pickle
import contextlib
@contextlib.contextmanager
def mutable_pickle(path, default=object):
try:
with open(path, "rb") as f:
obj = pickle.load(f)
except IOError, EOFError:
obj = default()
try:
yield obj
finally:
with open(path, "wb") as f:
pickle.dump(obj, f)
with mutable_pickle("fire.bin",
default=collections.OrderedDict) as d:
for row in rows:
d[tuple(row[:4])] = row
推荐阅读
- azure-data-factory - 尝试从 Azure 数据工厂中针对每个活动命中 API 时出现 429 错误
- python - 如果单击图像中框的周边,则绘制一个框
- php - index.php 没有获取 GET 变量,但 index.php?name=Joe 是(ESP8266)
- laravel - .isDirty 在提交并重新加载 InertiaJS 页面后为 true
- python - 如何在 python 脚本中运行 cookiecutter 命令时跳过“可以删除并重新下载吗?[是]:”问题?
- angular - Angular 使用 PrimeNG charjs 字体颜色问题
- java - 在java中读取txt文件时分离内容
- c# - Dotnet 6 集成测试的 Deps 文件丢失
- python - 使用来自另一个模型的信息更新 Django 表单的问题
- entity-framework-core - 向 EF Core 模型添加私有属性?