马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
import os
def test1(path,target):
os.chdir(path)
list1 = os.listdir('.')
for each in list1:
tuple1 = os.path.splitext(each)
if not os.path.isdir(each) and tuple1[1] =='.txt':
file_dict = dict() # 创建空的字典
f = open(os.path.join(path,each),encoding='utf-8')
count1 = 0 #行数
for file_content in f:
list2 = []
count1 += 1
index1 = file_content.find(target)
while index1 != -1:
list2.append(index1) #改用列表装位置
index1 = file_content.find(target,index1+1)
if list2 != []:
file_dict[count1] = list2
f.close()
if file_dict != dict():
keys = file_dict.keys()
keys = sorted(keys)
print('在文件[%s]发现关键字[%s]' %(os.path.join(path,each),target))
for file_keys in keys:
print ('在文件第%d行,第【%s】位置出现'%(file_keys,str(file_dict[file_keys])))
elif os.path.isdir(each):
test1(os.path.join(path,each),target)
os.chdir('..')
path = input('输入查询的初始路径:')
target = input('输入查询的关键字:')
test1(path,target)
除了 elif 缩进 还有个小问题,建议改成这样, open 中不用打开完整路径,否则填 . 时会报错
import os
def test1(path,target):
os.chdir(path)
list1 = os.listdir('.')
for each in list1:
tuple1 = os.path.splitext(each)
if not os.path.isdir(each) and tuple1[1] =='.txt':
file_dict = dict() # 创建空的字典
f = open(each,encoding='utf-8')
count1 = 0 #行数
for file_content in f:
list2 = []
count1 += 1
index1 = file_content.find(target)
while index1 != -1:
list2.append(index1) #改用列表装位置
index1 = file_content.find(target,index1+1)
if list2 != []:
file_dict[count1] = list2
f.close()
if file_dict != dict():
keys = file_dict.keys()
keys = sorted(keys)
print('在文件[%s]发现关键字[%s]' %(os.path.join(path,each),target))
for file_keys in keys:
print ('在文件第%d行,第【%s】位置出现'%(file_keys,str(file_dict[file_keys])))
elif os.path.isdir(each):
test1(os.path.join(path,each),target)
os.chdir('..')
path = input('输入查询的初始路径:')
target = input('输入查询的关键字:')
test1(path,target)
|