MaxyArthes MaxyArthes - 1 month ago 17
Python Question

search a word in a file and print only the text betwen two separator

I'm trying to code a searching fonction that gonna read a file and print name from it, without any other of the information on that line, I found out how to print the complete line only yet..

title = input("\n Enter a movie name: ")
with open("Data_Film") as f:
for line in f:
if title in line:
print(line)


here what look like the file it must search in :

1;Avatar;Science Fiction;3;2;3.99
2;Little Frog;Horror;2;3;3.99
...


so if I search a title, I would want it to check only from the first ";" to the second ";" as that where the movie name is and print it.

Thanks, hope my question was clear enought, english is not my native language.

Answer

Assuming your data file always will be in that format, and the title will always be after the second ';', you can use the native split function using the semicolon as the delimiter. This splits the line at the semicolons into an array, and the title is the second element.

title = input("\n Enter a movie name: ")
    with open("Data_Film") as f:
        for line in f:
            if title in line:
                print(line.split(';')[1])