简体   繁体   English

如何在Python中从文本文件读取特定行

[英]How to read a certain line from a text file in Python

I have a Python file and a text file with about 1000 names in it. 我有一个Python文件和一个文本文件,其中包含大约1000个名称。 I opened this file in Python, like this 我像这样用Python打开了这个文件

names = open('names.txt', 'r')

the text file is laid out as follows: 文本文件的布局如下:

Jason
Drake
Larry

How can I print the name 'Drake' onto the screen? 如何在屏幕上打印名称“ Drake”?

I know this question was answered previously, but I couldn't understand the explanations, as they were advanced. 我知道这个问题以前已经回答过,但是由于这些解释已经深入,我无法理解。 Please explain in an easy to understand manner, as I am new to programming. 由于我是编程新手,请以一种易于理解的方式进行说明。

names = open('names.txt', 'r')       # open the text file
namesList = names.read().split('\n') # read the entire file and split into a list
print(namesList[1])                  # print the element at index 1
names.close()                        # close the text file

Output: 输出:

Drake

If you are after just one line answer because you are going to read just one name: 如果您只回答一行,因为您将只读一个名字:

print(open('names.txt', 'r').read().split('\n')[1])

That might be an expensive thing to do, if you are doing it over and over again tho. 如果您一遍又一遍地做,那可能是一件昂贵的事情。

In either case, if you are using CPython, garbage collector will take care of closing the file. 在任何一种情况下,如果您使用的是CPython,则垃圾收集器将负责关闭文件。 If you are using some other implementation and you're not sure about that, you may use with : 如果您使用的是一些其它的实现和你不知道这一点,你可以使用with

with open('names.txt', 'r') as names:
    namesList = names.read().split('\n')
    print(namesList[1])
with open('names.txt') as names:
    names = names.read()
    names = names.split()
    print(names[1])

The first line opens the file in the variable names 第一行以变量names打开文件

The second line converts the file into text. 第二行将文件转换为文本。

The third line splits the text into a list, with the contents of each line being a new element. 第三行将文本分成一个列表,每行的内容是一个新元素。

The fourth line prints the name. 第四行显示名称。 Note that in Python, the first number is 0, so if you wanted to access the first name in the list it would be names[0] . 请注意,在Python中,第一个数字为0,因此,如果要访问列表中的第一个名称,它将为names[0]

Just look for Drake specifically and print it out: 只需专门寻找Drake并打印出来即可:

to_find = 'Drake'

with open('names.txt') as file:
    for line in map(str.strip, file):
        if line == to_find:
            print(line)

Which Outputs: 哪些输出:

Drake

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM