读取文本文件中的特定区域或字符串

问题描述 投票:0回答:2

我有一个我写过用户数据的文本文件。用户名,电子邮件和密码。

这就是用户文件现在的样子

[<<登录>>]

用户名:admin

密码:12345678

电子邮箱:[email protected]

[<<登录结束>>]

Now for the question.

如何告诉python只能专门读取密码?我的意思是,现在我们可能知道密码是什么以及它的长度是多少。但是,当我加密密码后,我应该如何读取密码并获得30多个字符的乱码?

python-3.x string passwords area
2个回答
0
投票

该行将包含密码,因此只需拆分一次并获取第二个元素:

In [20]: from simplecrypt import encrypt

In [21]: ciph = encrypt('password', "12345678")

In [22]: line = "Password: " + ciph

In [23]: line
Out[23]: 'Password: sc\x00\x01\x0cP\xa1\xee\'$"\xc1\x85\xe0\x04\xd2wg5\x98\xbf\xb4\xd0\xacr\xd3\\\xbc\x9e\x00\xf1\x9d\xbe\xdb\xaa\xe6\x863Om\xcf\x0fc\xdeX\xfa\xa5\x18&\xd7\xcbh\x9db\xc9\xbeZ\xf6\xb7\xd3$\xcd\xa5\xeb\xc8\xa9\x9a\xfa\x85Z\xc5\xb3%~\xbc\xdf'

In [24]: line.split(None,1)[1]
Out[24]: 'sc\x00\x01\x0cP\xa1\xee\'$"\xc1\x85\xe0\x04\xd2wg5\x98\xbf\xb4\xd0\xacr\xd3\\\xbc\x9e\x00\xf1\x9d\xbe\xdb\xaa\xe6\x863Om\xcf\x0fc\xdeX\xfa\xa5\x18&\xd7\xcbh\x9db\xc9\xbeZ\xf6\xb7\xd3$\xcd\xa5\xeb\xc8\xa9\x9a\xfa\x85Z\xc5\xb3%~\xbc\xdf'

In [25]: decrypt("password",line.split(None,1)[1])
Out[25]: '12345678'

In [26]: "12345678" == decrypt("password",line.split(None,1)[1])
Out[26]: True

当你迭代文件时,使用if line.startswith("Password") ...

with open(your_file) as f:
    for line in f:
       if line.startswith("Password"):
            password = line.rstrip().split(None,1)[1]
            # do your check

您可以使用dictpickle使用passwordas键,然后只需执行查找:


0
投票

如何告诉python只能专门读取密码?

data.txt中:

[<< LOGIN >>]

Username: admin

Password: 12345678

E-Mail: [email protected]

[<< LOGIN END >>]

[<< LOGIN >>]

Username: admin

Password: XxyYo345320945!@#!$@#!@#$%^%^^@#$%!@#$@!#41211 

E-Mail: [email protected]

[<< LOGIN END >>]

...

import re

f = open('data.txt')

pattern = r"""
    Password     #Match the word 'Password', followed by...
    \s*          #whitespace(\s), 0 or more times(*), followed by...
    :            #a colon
    \s*          #whitespace, 0 or more times...
    (.*)         #any character(.), 0 or more times(*).  The parentheses 'capture' this part of the match.
"""

regex = re.compile(pattern, re.X)  #When you use a pattern over and over for matching, it's more efficient to 'compile' the pattern.

for line in f:
    match_obj = regex.match(line)

    if match_obj:  #then the pattern matched the line
        password = match_obj.group(1)  #group(1) is what matched the 'first' set of parentheses in the pattern
        print password

f.close()

--output:--
12345678
XxyYo345320945!@#!$@#!@#$%^%^^@#$%!@#$@!#41211

正则表达式(或RE)指定一组与之匹配的字符串;通过此模块中的函数,您可以检查特定字符串是否与给定的正则表达式匹配(或者如果给定的正则表达式与特定字符串匹配,则归结为同一个字符串)。

正则表达式可以连接起来形成新的正则表达式;如果A和B都是正则表达式,那么AB也是正则表达式。通常,如果字符串p匹配A而另一个字符串q匹配B,则字符串pq将匹配AB。除非A或B包含低优先级操作,否则这是成立的; A和B之间的边界条件;或编号组参考。因此,复杂的表达式可以很容易地用比这里描述的更简单的原始表达式构造。有关正则表达式的理论和实现的详细信息,请参阅上面引用的Friedl一书,或几乎任何有关编译器构造的教科书。

下面是正则表达式格式的简要说明。有关更多信息和更温和的演示文稿,请参阅正则表达式HOWTO。

https://docs.python.org/3/library/re.html#module-re

© www.soinside.com 2019 - 2024. All rights reserved.