简体   繁体   English

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

[英]How to read txt file in python line by line and set each line to a variable

I have dictionary code which is programmed in python and a word list, the python code which decrypts a specific encrypted text is here: 我有用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'

I want the code to loop through all lines in the words.txt and try them to check if they are the right value for the decryption process, this code stops when it reads the first line and it output wrong password 我希望代码循环遍历word.txt中的所有行,并尝试检查它们是否是解密过程的正确值,该代码在读取第一行并输出wrong password时停止

If you use rstrip() it removes all the whitespaces along with the new line( \\n ). 如果使用rstrip()它将删除所有空格以及新行( \\n )。 So use rstrip('\\n') to remove the newlines only. 因此,使用rstrip('\\n')仅删除换行符。 As you want to loop it put the logic inside a for loop. 当您要循环时,将逻辑放入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()

Reading line by line happens simply like this 逐行读取就像这样

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

Does this solve your problem? 这样可以解决您的问题吗?

Each line in a file will contain the newline escape character: \\n at the end of the line. 文件中的每一行都将包含换行符: \\n
Here's how you can loop over the file: 您可以通过以下方法遍历文件:

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)

Hope it helps. 希望能帮助到你。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM