python - 从文件索引中读取特定行

如何从文件中读取特定行?

user.txt:

root
admin
me
you

当我做

def load_user():
       file = open("user.txt", "r")
       nextuser_line = file.readline().strip()
       print(nextuser_line)
       file.close()

root 将被打印,但我想从文件中读取 admin。所以我尝试使用 [1] 读取下一行索引

def load_user():
       file = open("user.txt", "r")
       nextuser_line = file.readline().strip()
       print(nextuser_line[1])
       file.close()

不是打印 'admin',而是输出来自 'root''o',而不是文件的下一行。

我究竟做错了什么?

回答1

readline() 读取第一行。要通过索引访问行,请使用 readlines()

def load_user():
    file = open("user.txt", "r")
    lines = file.readlines()
    print(lines[1])
    file.close()
>>> load_user()
'admin'

要从行中删除 \n,请使用:

lines = [x.strip() for x in file]

相似文章

随机推荐

最新文章