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

时间:2016-02-12 13:12:55

标签: 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'

我希望代码循环遍历words.txt中的所有行,并尝试检查它们是否是解密过程的正确值,此代码在读取第一行时停止并输出wrong password

5 个答案:

答案 0 :(得分:0)

如果您使用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()

答案 1 :(得分:0)

逐行阅读就像这样

chr1    822979  822980  CLL6.08_1_snv   88.2    +
chr1    1052781 1052782 CLL6.08_2_snv   388.9   +
chr1    1216196 1216197 CLL6.08_3_snv   625 +
chr1    5053847 5053848 CLL6.08_4_snv   722.2   +
chr1    5735093 5735094 CLL6.08_5_snv   138.9   +

答案 2 :(得分:0)

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

certifi

答案 3 :(得分:0)

f = open('<filepath>', 'r')
for line in f.readlines():
    secret = line
    # do something with the line
f.close()

这会解决您的问题吗?

答案 4 :(得分:0)

文件中的每一行都将包含换行符转义符:\n在行尾 以下是循环文件的方法:

f = open('words.txt')

for line in f:
    secret = line[:-1] # will extract a substring not containing the newline char

    # then do what you want with secret like:
    do_decoding(secret)

希望它有所帮助。