简体   繁体   中英

How would I allow a user to access a specific line in a file in python?

I have used Python to write a program to open a file and then ask a user input to check if a certain string of characters is in that file.

I am confused on how I would allow the program to print the specific line in which those string of characters they requested for.

That is the part I need help on.

You can do that the following way:

file = open('textfile.txt', 'r')
string = input("Enter string to search in file")
lineCount = 0
for line in file:
    lineCount += 1
    if string in line:
        print(lineCount)

Actually, I meant to print the whole text in which the string the user requested Sorry.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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