【发布时间】:2016-10-21 12:28:24
【问题描述】:
只是关于我正在使用的以下代码的一个问题——效果很好,但希望在获得结果时获得更多信息
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
如果我搜索“自行车”
脚本给了我一行,但也想在上面包含标题,其中包含 / 在其列表中
再次感谢
丹
【问题讨论】:
标签: regex python-3.x search