在Python阅读文本文件时,阵列中的每一行的元素 [英] Each line an element in an array when reading text file in Python

查看:328
本文介绍了在Python阅读文本文件时,阵列中的每一行的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在写一个程序,评估一个输入的密码的强度。一个功能将密码比较的,我有一个万股普通密码的主列表。

在读取文本文件时,我使用:

 进口IO与io.open('MasterList.txt',编码='的Latin-1')为myfile的:
    数据= myfile.read()取代(的'\\ n','')

但打印像数据[0] 给我的第一个的字符的不是第一的的。我怎样才能让数据是一个列表,其中每个元素是从文本文件中的行?每一行 \\ n 结束。我必须以某种方式使用它作为一个新的行开始标记所在?


解决方案

 进口IO数据= []
与io.open('MasterList.txt',编码='的Latin-1')为myfile的:
    因为我在myfile.readlines():
        data.append㈠

然后就可以循环数据,并将其与输入密码比较。您可以使用:

 如果密码数据:
    打印数据发现密码

I'm writing a program that will assess an entered password's strength. One function will compare the password to a master list of a million common passwords that I have.

When reading the text file, I'm using:

import io

with io.open('MasterList.txt', encoding='latin-1') as myfile:
    data=myfile.read().replace('\n', '')

But printing something like data[0] gives me the first character instead of the first line. How can I make data be a list where each element is a line from the text file? Each line ends in \n. Do I have to somehow use that as the marker of where a new line begins?

解决方案

import io

data = []
with io.open('MasterList.txt', encoding='latin-1') as myfile:
    for i in myfile.readlines():
        data.append(i)

Then you can loop data and compare it with the entered password. You can use:

if password in data:
    print "Password found in data"

这篇关于在Python阅读文本文件时,阵列中的每一行的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆