无法从文本文件中打印特定行 [英] Can't print a specific line from text file

查看:107
本文介绍了无法从文本文件中打印特定行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我目前有这段代码可以读取一个如下所示的account.txt文件:

So I currently have this code to read an accounts.txt file that looks like this:

username1:password1
username2:password2
username3:password3

然后让我(感谢这里的一名成员)读取accounts.txt文件,并将其拆分为用户名和密码,以便以后进行打印.当我尝试使用用户名和密码分别用以下代码打印第1行时:

I then have this (thanks to a member here) read the accounts.txt file and split it at the username and password so I can later print it. When I try to print line 1 with the username and password separate with this code:

with open('accounts.txt') as f:

    credentials = [x.strip().split(':') for x in f.readlines()]



for username,password in credentials:

    print username[0]
    print password[0]

它打印出:

j
t
a
2
a
3

(这是我在文本文件中包含的三行,已正确分割,但是它仅打印所有行,并且仅打印每行的第一个字母.)

(These are the three lines I have in the text file, properly split, however it's printing all the lines and only the first letter of each line.)

我尝试了几种不同的方法,但都没有碰到运气.任何人都知道该怎么做?

I've tried a few different methods with no luck. Anyone have an idea on what to do?

感谢您的所有帮助.真的很感激.这是我的第二天编程,对于这样一个简单的问题我深表歉意.

Thank you for all your help. It's really appreciated. This is my second day programming and I apologize for such a simple question.

推荐答案

usernamepassword是字符串.对字符串执行此操作时,将获得字符串中的第一个字符:

username and password are strings. When you do this to a string, you get the first character in the string:

username[0]

不要那样做.只是print username.

一些进一步的解释. credentials是字符串列表的列表.当您打印出来时,它看起来像这样:

Some further explanation. credentials is a list of lists of strings. It looks like this when you print it out:

[['username1', 'password1'], ['username2', 'password2'], ['username3', 'password3']]

要获取一个用户名/密码对,可以执行以下操作:print credentials[0].结果将是这样:

To get one username/password pair, you could do this: print credentials[0]. The result would be this:

['username1', 'password1']

或者,如果您执行了print credentials[1],则此操作:

Or if you did print credentials[1], this:

['username2', 'password2']

您还可以执行名为拆包"的操作,这就是您的for循环所要做的.您也可以在for循环外执行此操作:

You can also do a thing called "unpacking," which is what your for loop does. You can do it outside a for loop too:

username, password = credentials[0]
print username, password

结果将是

username1 password1

同样,如果您采用'username1'这样的字符串并采用如下单个元素:

And again, if you take a string like 'username1' and take a single element of it like so:

username[0]

您会收到一个字母u.

这篇关于无法从文本文件中打印特定行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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