2016-03-28 6 views
0

コンピュータのファイルで選択できる別の.txtファイルで特定の文字列を検索したいのですが。.txtファイルで文字列を検索する

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

をしかし、私は自分で全体ファイルのパスを足すことなく、ファイルを選択するために、これらのコード行を追加するとき、私は自分でパスを書いてしなければならない、と::このコードは、実際に動作する

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() 
ここで

がトレースバックです:os.path.realpath()パスを与えるので

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 

私は右、間違っているものを見ることができませんか?私は私の問題はaskopenfile()から来て、私はどのような種類のデータが返されたのかわかりません。 私に手を差し伸べていただければ幸いです。

答えて

1

askopenfile()ファイルを返さない名前;ファイルオブジェクトを返します。つまり、自分で開く必要はありません。あなたはこれを行うことができます:あなたはとにかく変数名としてfileを使用すべきではない

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() 

、Python2で、それはビルトインタイプをシャドウので。

関連する問題