无法打印文本文件中的特定行

发布于 2024-12-31 20:55:57 字数 622 浏览 1 评论 0 原文

所以我目前有这段代码来读取一个类似这样的accounts.txt 文件:

username1:password1
username2:password2
username3:password3

然后我(感谢这里的一位成员)读取accounts.txt 文件并在用户名和密码处将其拆分,以便稍后可以打印它。当我尝试使用以下代码单独打印第 1 行的用户名和密码时:

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

这些是我在文本文件中的三行,正确分割,但是它打印所有行,仅打印第一个字母每行。)

我尝试了几种不同的方法,但没有成功。有人知道该怎么做吗?

感谢您的帮助。真的很感激。这是我第二天的节目,对于这样一个简单的问题我深表歉意。

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

username1:password1
username2:password2
username3:password3

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]

It prints out this:

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

欲拥i 2025-01-07 20:55:57

用户名密码是字符串。当您对字符串执行此操作时,您将获得字符串中的第一个字符:

username[0]

不要这样做。只需打印用户名

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

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

要获取一对用户名/密码,您可以执行以下操作:打印凭证[0]。结果将是这样的:

['username1', 'password1']

或者,如果您执行了打印凭据[1],则为:

['username2', 'password2']

您还可以执行一项称为“拆包”的操作,这就是 for 循环的作用。您也可以在 for 循环之外执行此操作:

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

结果将是

username1 password1

再一次,如果您采用像 'username1' 这样的字符串并采用其中的单个元素,如下所示:

username[0]

您会得到一个字母,<代码>u

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

username[0]

Don't do that. Just print username.

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']]

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

['username1', 'password1']

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

['username2', 'password2']

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

The result would be

username1 password1

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

username[0]

You get a single letter, u.

夜唯美灬不弃 2025-01-07 20:55:57

首先,我想说,如果这是您第二天的编程,那么使用 with 语句和 列表已经理解了

正如其他人已经指出的那样,由于您使用 [] 索引与包含 str 的变量,因此它将 str 视为如果它是一个数组,那么您将获得指定索引处的字符。

我想我应该指出几件事:

1)您不需要使用 f.readline() 来迭代文件,因为文件对象 f是一个可迭代对象(它定义了 __iter__ 方法,您可以使用 getattr(f, '__iter__') 检查该方法。因此您可以这样做:

with open('accounts.txt') as f:
    for l in f:
        try:
            (username, password) = l.strip().split(':')
            print username
            print password
        except ValueError:
            # ignore ValueError when encountering line that can't be
            # split (such as blank lines).
            pass

2)您还提到你“好奇如果有没有办法只打印文件的第一行?或者在这种情况下选择第二行、第三行等?”

islice(iterable[, start], stop[, step])< itertools 包中的 /code> 函数作品非常适合,例如,只获得第二个和第二个。第三行(记住索引从 0 开始!!!):

from itertools import islice
start = 1; stop = 3
with open('accounts.txt') as f:
    for l in islice(f, start, stop):
        try:
            (username, password) = l.strip().split(':')
            print username
            print password
        except ValueError:
            # ignore ValueError when encountering line that can't be
            # split (such as blank lines).
            pass

或者获取每隔行:

from itertools import islice
start = 0; stop = None; step = 2
with open('accounts.txt') as f:
    for l in islice(f, start, stop, step):
        try:
            (username, password) = l.strip().split(':')
            print username
            print password
        except ValueError:
            # ignore ValueError when encountering line that can't be
            # split (such as blank lines).
            pass

花时间学习 itertools (及其 食谱!!!);它会简化你的代码。

First, I'd like to say if this is your second day programming, then you're off to a good start by using the with statement and list comprehensions already!

As the other people already pointed out, since you are using [] indexing with a variable that contains a string, it treats the str as if it were an array, so you get the character at the index you specify.

I thought I'd point out a couple of things:

1) you don't need to use f.readline() to iterate over the file since the file object f is an iterable object (it has the __iter__ method defined which you can check with getattr(f, '__iter__'). So you can do this:

with open('accounts.txt') as f:
    for l in f:
        try:
            (username, password) = l.strip().split(':')
            print username
            print password
        except ValueError:
            # ignore ValueError when encountering line that can't be
            # split (such as blank lines).
            pass

2) You also mentioned you were "curious if there's a way to print only the first line of the file? Or in that case the second, third, etc. by choice?"

The islice(iterable[, start], stop[, step]) function from the itertools package works great for that, for example, to get just the 2nd & 3rd lines (remember indexes start at 0!!!):

from itertools import islice
start = 1; stop = 3
with open('accounts.txt') as f:
    for l in islice(f, start, stop):
        try:
            (username, password) = l.strip().split(':')
            print username
            print password
        except ValueError:
            # ignore ValueError when encountering line that can't be
            # split (such as blank lines).
            pass

Or to get every other line:

from itertools import islice
start = 0; stop = None; step = 2
with open('accounts.txt') as f:
    for l in islice(f, start, stop, step):
        try:
            (username, password) = l.strip().split(':')
            print username
            print password
        except ValueError:
            # ignore ValueError when encountering line that can't be
            # split (such as blank lines).
            pass

Spend time learning itertools (and its recipes!!!); it will simplify your code.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文