Find a String in a .txt file
Question: I want to find a specific string in different .txt files which I can choose in
my computer's files. This code actually work :

    
    
    string = "example" 
    fichier = open(file_path,"r")
    for line in fichier:
        if string in line:
            print string
    fichier.close()
    

But I have to wrote the path by myself, and when I add those code lines in
order to select the file without writting the whole file's path by myself :

    
    
    from Tkinter import Tk
    from tkFileDialog import askopenfile
    import os
    
    Tk().withdraw()
    file = askopenfile()
    file_path = os.path.realpath(file)
    string = "example" 
    fichier = open(file_path,"r")
    for line in fichier:
        if string in line:
            print string
    fichier.close()"
    

Here is the traceback

    
    
    Traceback (most recent call last):
          File "C:\Users\WinPython-64bit-2.7.10.3\python-2.7.10.amd64\Lib\sip-4.18.dev1603251537\fichier txt.py", line 13, in <module>
            file_path = os.path.realpath(file)
          File "C:\Users\WinPython-64bit-2.7.10.3\python-2.7.10.amd64\lib\ntpath.py", line 488, in abspath
            path = _getfullpathname(path)
        TypeError: coercing to Unicode: need string or buffer, file found
    

I can't see what's wrong, because the os.path.realpath() gives a path right ?
I guess my problem comes from the askopenfile, I can't find what kind of data
it returned. I would appreciate if you give me a hand please.


Answer: `askopenfile()` does not return a file _name_ ; it returns a file _object_.
That means that you don't need to do the opening yourself. You can just do
this:

    
    
    from Tkinter import Tk
    from tkFileDialog import askopenfile
    import os
    
    Tk().withdraw()
    fichier = askopenfile()
    string = "example" 
    for line in fichier:
        if string in line:
            print string
    fichier.close()
    

You shouldn't be using `file` as a variable name anyway, because in Python2 it
shadows the built-in type.

