python - 如何在临时文件中使用 FOR 创建循环?
问题描述
我正在处理一个加密文件,但我无法创建一个循环for
以便在它被关闭和删除之前读取它。
我的意图是读取加密文件中给出的数据并循环它以将每一行分配给一个变量。
每当我执行我的代码时,Python 都会直接完成,而不使用解密的信息;我相信这是因为with
命令在循环开始之前将其关闭。
这就是我想要的,不工作,也没有错误:
with open(input_file, 'rb') as fp:
data = fp.read()
fernet = Fernet(key)
encrypted = fernet.decrypt(data)
with tempfile.TemporaryFile() as fp:
fp.write(encrypted)
for url in fp: #Python ignores the tempfile. I belive it is closed in the previous line.
segment = url.strip()
url = 'https://docs.python.org/3.3/tutorial/' + segment
filename = segment + '.html'
filePath = pjoin('Data/' + filename)
response = urlopen(url)
webContent = response.read()
html_content = urlopen(url).read()
matches = re.findall(b'string', html_content);
if len(matches) == 0:
print(segment + ' unchanged.')
else:
with open(filePath, 'wb') as w:
w.write(webContent)
这是工作代码(对不起,试图缩短但不能):
with open(input_file, 'rb') as fp:
data = fp.read()
fernet = Fernet(key)
encrypted = fernet.decrypt(data)
with open(output_file, 'wb') as fp:
fp.write(encrypted)
with open(output_file) as fp:
for url in fp:
segment = url.strip()
url = 'https://docs.python.org/3.3/tutorial/' + segment
filename = segment + '.html'
filePath = pjoin('Data/' + filename)
response = urlopen(url)
webContent = response.read()
html_content = urlopen(url).read()
matches = re.findall(b'string', html_content);
if len(matches) == 0:
print(segment + ' unchanged.')
else:
with open(filePath, 'wb') as w:
w.write(webContent)
两个示例的标题(除了使其更短):
#python 3.6.6
from urllib.request import urlopen
import urllib.request
from os.path import join as pjoin
import re, os, sys, tempfile, six, ctypes, time, fileinput
from cryptography.fernet import Fernet
print("[*] Checking list.dat for consistency . . .")
key = b'wTmVBRLytAmlfkctCuEf59K0LDCXa3sGas3kPg3r4fs=' #Decrypt list.dat
input_file = 'List.dat'
output_file = 'List.txt'
List.txt 内容:
errors
classes
stdlib
有什么提示吗?
解决方案
问题是一旦你写入文件,“文件指针”就在文件的末尾。没有什么可读的。
您可以使用该seek
方法将文件指针重新定位在开头。或者,关闭并重新打开文件(如在您的工作代码中)会将指针定位在文件的开头。
推荐阅读
- android - 如何将具有 json 的活动转换为片段
- php - 如何在 laravel 中使用多级 json 进行查询
- javascript - 将 URL 参数发布到触发显示自动完成建议的输入文本框
- javascript - 将 Stylelint 与 Vue.js 集成
- javascript - 使用 jQuery 设置元素的 onclick 属性时遇到问题
- spring-cloud-gateway - 如何为路由设置默认前缀?
- javascript - jQuery滚动到按钮单击中的部分
- ios - 检查应用程序是否通过 iOS 上的今日小部件启动...?
- node.js - 将 Excel 日期转换为 Moment 日期会产生错误的年份输出
- mysql - Grafana 中使用 mysql 数据库制作图形时出现错误 1064