如何在python中逐行读取txt文件并将每一行设置为一个变量

2024-04-19 12:27:54 发布

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

我有用python编写的字典代码和一个单词列表,解密特定加密文本的python代码如下:

from Crypto.Cipher import AES
import base64
import os

BLOCK_SIZE = 32

PADDING = '{'

# Encrypted text to decrypt
encrypted = "t0ed+TDTf4e1V3Vz94nAN+nj1uDgMPZnfd7BDyBoy/GeGk6LiImMBPPHvN8DcLgIhWo4ByqxpZby99nQpU8KuA=="

DecodeAES = lambda c, e: c.decrypt(base64.b64decode(e)).rstrip(PADDING)

f = open('words.txt')

for line in f.readlines():
    secret = line.rstrip('\n')
f.close()

if (secret[-1:] == "\n"):
    print "Error, new line character at the end of the string. This will not match!"
elif (len(secret) >= 32):
    print "Error, string too long. Must be less than 32 characters."
else:
    # create a cipher object using the secret
    cipher = AES.new(secret + (BLOCK_SIZE - len(secret) % BLOCK_SIZE) * PADDING)

    # decode the encoded string
    decoded = DecodeAES(cipher, encrypted)

    if (decoded.startswith('FLAG:')):
        print "\n"
        print "Success: "+secret+"\n"
        print decoded+"\n"
    else:
        print 'Wrong password'

我希望代码在文字.txt并尝试检查它们是否是解密过程的正确值,此代码在读取第一行时停止并输出wrong password


Tags: the代码importsizesecretstringlineblock
3条回答

逐行阅读的过程就是这样

with open('words.txt', 'r') as f:
    for line in f:
        secret = line #Normally there are no \n at the end

        #Use this is in case you still get the \n
        #secret = line.rstrip('\n') 

尝试用空字符串替换换行符:

line = f.readline().replace('\n','')

如果使用rstrip(),它会删除新行(\n)中的所有空白。所以使用rstrip('\n')只删除换行符。当您想要循环时,将逻辑放入for循环中。在

f = open('words.txt')

for line in f.readlines():
    secret = line.rstrip('\n')
    if (secret[-1:] == "\n"):
        print "Error, new line character at the end of the string. This will not match!"
    elif (len(secret) >= 32):
        print "Error, string too long. Must be less than 32 characters."
    else:
    # create a cipher object using the secret
        cipher = AES.new(secret + (BLOCK_SIZE - len(secret) % BLOCK_SIZE) * PADDING)

    # decode the encoded string
        decoded = DecodeAES(cipher, encrypted)

        if (decoded.startswith('FLAG:')):
            print "\n"
            print "Success: "+secret+"\n"
            print decoded+"\n"
            break
        else:
            print 'Wrong password'
f.close()

相关问题 更多 >