[python] Search for a string in a file

phic -  
 ccadic -
Hello.

I'm learning Python and I would like to write a small script that opens a file and searches for strings in it (which will be lines of code in another language) and then displays them with a print statement afterwards. How should I go about it?

Thank you in advance.

19 answers

  1. sebsauvage Posted messages 33284 Registration date   Status Moderator Last intervention   15 684
     
    Hello !

    Here is a simple example:
    We are looking for lines containing "coucou" in the file fichier.txt and displaying them:

    #!/usr/bin/python # -*- coding: iso-8859-1 -*- chaine = "coucou" # Text to search file = open("fichier.txt","r") for ligne in fichier: if chaine in ligne: print ligne file.close()


    --
    “Life is short - You need Python” -- Bruce Eckel, member of the ANSI C++ committee
    30
    1. phic
       
      Yes, interesting. And if I want to search for multiple strings and display them line by line. I need to create a class, right? I can't figure out how to do that. I can create another variable with string2 = "thing" and then use an elif to print the line. But if there are more than 30 types of strings to search for, that might take a long time.
      Do you have any ideas?

      Thank you for your help.
      0