【发布时间】:2018-10-31 14:57:53
【问题描述】:
我正在处理一个加密文件,但我无法使用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
有什么提示吗?
【问题讨论】:
-
为什么要先将
encrypted写回临时文件?为什么不直接使用解密的数据(我不确定你为什么将其命名为encrypted)然后将其写回filePath? -
我试过了,其实这就是我最初想要的,但找不到方法。这就是我继续使用
write方法的原因。而且我改成解密了两次,但是我擦写和ctrl+z等等,又回到encrypted。
标签: python python-3.x for-loop temp