如何在临时文件中用FOR创建循环?

2024-04-26 09:56:43 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在处理一个加密的文件,但是我无法使用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)

这是工作代码(抱歉,试图缩短但无法):

^{pr2}$

要使标题分开(两个示例都缩短):

#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'

在列表.txt内容:

errors
classes
stdlib

有什么提示吗?


Tags: fromimporturlforreadhtmlaswith
2条回答

问题是一旦你写了文件,“文件指针”就在文件的结尾。没什么可看的。在

可以使用^{} method将文件指针重新定位在开头。或者,关闭和重新打开文件(如在您的工作代码中)将指针定位在文件的开头。在

@LarryLustig几乎回答了为什么您的代码不能工作,但是在我看来,如果您完全消除了临时文件(这不应该是必要的),您甚至不需要担心光标。请参阅下面对您所需代码所做的更改的注释。在

# We'll use os.linesep to get the line terminator string for your os.
import os

...

with open(input_file, 'rb') as fp:
  data = fp.read()

fernet = Fernet(key)

# decode your decrypted bytes into strings.  Change 'utf-8' into whichever file encoding you're using if necessary.
decrypted = fernet.decrypt(data).decode('utf-8')

# Don't write to a temp file
# Iterate directly on each line of the extracted data
for url in decrypted.split(os.linesep): 
    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)

或者,如果您确定文件中使用的行终止符是什么(例如\r\n,或\n),那么您可以完全不使用os.linesep。在

相关问题 更多 >