|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
本帖最后由 被巧击的键盘丶 于 2014-8-1 14:20 编辑
我在桌面运行的时候会报这个错误:
不知道怎么解决我在其他文件夹下运行不会报错。
以下是代码:
import os
def find_keyword(path,keyword):
file = open(path)
line = 1#行数
location = []#储存文本出现位置
for details in file:
start = 0
while True:
index = details.find(keyword,start)
if index == -1:
if location != []:
print('=' * 50)
print('在文件【{0}】中找到关键字【{1}】'.format(path,keyword))
print('关键字出现在第 {0} 行,第 {1} 个位置'.format(line,location))
line += 1
location = []
break
else:
location.append(index + 1)
start = index + 1
file.close()
keyword = input('请将该脚本放于待查找的文件夹内,请输入关键字:')
ins = input('请问是否需要打印关键字【{0}】在文件中的具体位置(YES/NO):'.format(keyword))
file_list = os.walk(os.getcwd())
if ins in ['YES','yes']:
for file in file_list:
if file[2] != []:
for each in file[2]:
ext = os.path.splitext(each)
if '.txt' in ext[1]:
path = os.path.join(file[0],each)
find_keyword(path,keyword)
else:
print('用户取消操作')
|
|