Walter
Walter

Reputation: 321

Searching or a specific substring in a file

This question is possibly a duplicate but any answers i find don't seem to work. I have a .txt file full of this layout:

artist - song, www.link.com

artist2 - song2, www.link2.com

This is my general purpose:

uinput = input("input here: ")

save = open("save.txt", "w+")
ncount = save.count("\n")

for i in range(0, ncount):
    t = save.readline()
    if uinput in t:
        print("Your string " uinput, " was found in" end = "")        
        print(t)

My intention is: If the userinput word was found in a line then print the entire line or the link.

Upvotes: 0

Views: 87

Answers (3)

Rachit kapadia
Rachit kapadia

Reputation: 701

You can use list comprehension to fetch the lines containing user input words. use below code:

try:
    f = open("file/toyourpath/filename.txt", "r") 
    data_input = raw_input("Enter your listed song from file :");
    print data_input
    fetch_line = [line for line in f if data_input in line]
    print fetch_line
    f.close()
except ValueError, e:
    print e

Upvotes: 0

cs95
cs95

Reputation: 403050

  1. You want to read the file, but you are opening the file in write mode. You should use r, not w+

  2. The simplest way to iterate over a file is to have a for loop iterating directly over the file object

  3. Not an error but a nitpick. You do not close your file. You can remedy this with with.. as context manager


uinput = input("input here: ")

with open("save.txt", "r") as f:
    for line in f:
        if uinput in line:
            print('Match found')

Upvotes: 4

Mohd
Mohd

Reputation: 5613

You can use list-comprehension to read the file and get only the lines that contain the word, for example:

with open('save.txt', 'r') as f:
    uinput = input("input here: ")
    found = [line.rstrip() for line in f if uinput.lower() in line.lower()]
    if found:
        print('Found in these lines: ')
        print('\n'.join(found))
    else:
        print('Not found.')

If you want to print the link only, you can use:

found = [line.rstrip().split(',')[1] for line in f if uinput.lower() in line.lower()]

Upvotes: 1

Related Questions