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()
,我無法找到它返回的數據類型。 如果您請給我一隻手,我將不勝感激。