1
只是對我使用的代碼以下幾部件有點問題 - 得到結果Python 3。當搜索TXT文件 - -aim也拿不到冠軍,以及搜索文本
當運行完美,但希望能得到更多的信息search_path = ('location of myfile.txt')
file_type = ('myfile.txt')
search_str = input("Enter the search string : ").strip()
if not (search_path.endswith("/") or search_path.endswith("\\")):
search_path = search_path + "/"
if not os.path.exists(search_path):
search_path ="."
for fname in os.listdir(path=search_path):
# Apply file type filter
if fname.endswith(file_type):
# Open file for reading
fo = open(search_path + fname)
# Read the first line from the file
line = fo.readline()
# Initialize counter for line number
line_no = 1
# Search for string with lower case
index = line.find(search_lower)
if (index != -1) :
print(fname, "[", line_no, ",", index, "] ", line, sep="")
# Read next line
line = fo.readline()
# Increment line counter
line_no += 1
# Close the files
fo.close()
= ===============================
myfile.txt
/This is in the first one- - -1 : Color
Name Value
--------------- ---------------------------------------------------------------------------------------
Blue Car
Green Drive
Red Bike
/This is in the 2nd one- - -2 : Gears
Name Value
--------------- ---------------------------------------------------------------------------------------
Auto Car
Man Drive
None Bike
如果我做一個搜索 '自行車'
該腳本給了我一行,但也想包含上面包含/在其列表中的標題
再次感謝
丹
我喜歡你的解決方案,但我會建議使用'line.startswith( '/')'使它有點更清晰的閱讀。 – xulfir
謝謝所有人 - 將檢查出 – olearydc
只是爲了讓你知道 - - 完美的工作,正是我正在尋找的 - - 再次感謝對兩者的快速反應 – olearydc