30讲第四题
import osimport os.path
def search(path,key):
os.chdir(path)
filelist=os.listdir()
for each in filelist:
if os.path.splitext(each)=='.txt':
f=open(os.getcwd()+'\\'+each)
line=0
for each_line in f:
line+=1
if key in each_line:
position=[]
for eachkey in key:
posision.append(each_line.find(eachkey))
print('关键字出现在第'+str(line)+'第'+position+'位置')
f.close()
elif os.path.isdir(each)==1:
path=os.getcwd()+'\\'+each
search(path,key)
os.chdir('..')
path=input('请输入路径:')
key=input('请输入关键字:')
search(path,key)
显示UnicodeDecodeError: 'gbk' codec can't decode byte 0xab in position 51: illegal multibyte sequence
不知道哪里错了 第八行改成:
f=open(os.getcwd()+'\\'+each, encoding = "utf-8") f=open(os.getcwd()+'\\'+each,encoding="utf-8")
再试试 import os
import os.path
def search(path,key):
os.chdir(path)
filelist=os.listdir()
for each in filelist:
if os.path.splitext(each)=='.txt':
f=open(os.getcwd()+'\\'+each,encoding='utf-8')
line=0
for each_line in f:
line+=1
if key in each_line:
position=[]
for eachkey in key:
posision.append(each_line.find(eachkey))
print('关键字出现在第'+str(line)+'第'+position+'位置')
f.close()
elif os.path.isdir(each)==1:
path=os.getcwd()+'\\'+each
search(path,key)
os.chdir('..')
path=input('请输入路径:')
key=input('请输入关键字:')
search(path,key)
昨非 发表于 2021-3-7 11:14
f=open(os.getcwd()+'\\'+each,encoding="utf-8")
再试试
UnboundLocalError: local variable 'position' referenced before assignment
又出现了这个 Blizzard0319 发表于 2021-3-7 11:18
UnboundLocalError: local variable 'position' referenced before assignment
又出现了这个
局部变量与全局变量同名,改一下下变量的名字 posision.append(each_line.find(eachkey))
第15行这里,position,拼写错误吧
页:
[1]