2016-03-28 119 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() 

這裏是回溯:

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 

我看不出有什麼不對,因爲os.path.realpath()給出了一個路徑,對不對?我想我的問題來自askopenfile(),我無法找到它返回的數據類型。 如果您請給我一隻手,我將不勝感激。

回答

1

askopenfile()不返回文件名稱;它返回一個文件對象。這意味着你不需要自己打開。你可以這樣做:

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

你不應該使用file作爲變量名,無論如何,因爲它Python2陰影內置式。