|
|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
编码:
import os
def sou(path,key):
long=len(key)
for each in os.listdir(path):
if os.path.exists(path+each+'\\'):
sou(path+each+'\\',key)
else:
a=os.path.splitext(each)
if a[1]=='.txt' :
f=list(open(path+each,'r'))
hang=1
count=[-(long-1)]
for eachs in f:
while eachs.find(key)>=0:
count.append(eachs.find(key)+count[-1]+long)
print('{0}处发现关键字{1},于第{2}行的{3}处'.format(path+each,key,hang,count[1:]))
eachs=each[eachs.find(key)+long:]
hang+=1
path=input('请输入路径:')
key=input('请输入关键字:')
sou(path,key)
此程序在搜寻某些地方的字符串时没报错,但有时报错,咋回事?求助
输入如下:
请输入路径:e:\
请输入关键字:小甲鱼
报错如下:
Traceback (most recent call last):
File "C:\Users\Administrator\Desktop\python试验场\1.py", line 22, in <module>
sou(path,key)
File "C:\Users\Administrator\Desktop\python试验场\1.py", line 6, in sou
sou(path+each+'\\',key)
File "C:\Users\Administrator\Desktop\python试验场\1.py", line 6, in sou
sou(path+each+'\\',key)
File "C:\Users\Administrator\Desktop\python试验场\1.py", line 6, in sou
sou(path+each+'\\',key)
File "C:\Users\Administrator\Desktop\python试验场\1.py", line 6, in sou
sou(path+each+'\\',key)
File "C:\Users\Administrator\Desktop\python试验场\1.py", line 10, in sou
f=list(open(path+each,'r'))
UnicodeDecodeError: 'gbk' codec can't decode byte 0xa1 in position 1444: illegal multibyte sequence
可能是编码解码有问题,怎么解决?
- f=list(open(path+each,'r'))#这里改成下面试试
- patheach=path+each
- f=list(open(patheach.encode('gbk'),'r')
复制代码
|
|