Python 30讲课后4题
import osdef find_fun(path, word):
i = 0
count = []
for each in os.listdir(path):
each_path = os.path.join(path, each)
if os.path.isfile(each_path):
each_list = os.path.splitext(each)
if str(each_list) == '.txt':
print('=================================================')
print(f'在文件【{each_path}】中找到关键字【{word}】')
fun(each_path, word)
else:
next_path = each_path
find_fun(next_path, word)
def fun(each_path, word):
i = 0
count = []
file = open (each_path)
file_list = list(file)
for each_line in file_list:
i += 1
index = each_line.find(word)
if index != -1:
count.append(index)
for m in range(count[-1], len(each_line)):
if index != -1:
index = each_line.find(word, (count[-1] + 1), len(each_line))
print(f'关键字出现在第 {i} 行,第{count}位置')
count.clear()
word = input('请将该脚本放于待查找的文件夹内,请输入关键字:')
path = os.getcwd()
print (f'请问是否需要打印关键字【{word}】在文件中的具体位置(YES\\NO):', end = '')
judge = input()
if judge == 'YES' or judge == 'yes':
find_fun(path, word)
运行报错编码错误,什么叫编码错误,怎么改正
路径有中文字的问题吗
还有什么其他问题吗
第20行
file = open(each_path, encoding='utf-8') suchocolate 发表于 2021-5-12 17:56
第20行
试了 ,不行
好像是因为我的目标文件有点是utf8 编码有的是gbk编码 如果是用pycharm编写的话,可以试试到文件--设置--编辑器--文件编码,你会看左上两个和下面一个框写着gbk,把这三个改成utf-8。或者你把报错的代码发一下。。。 import os
def find_fun(path, word):
for each in os.listdir(path):
each_path = os.path.join(path, each)
if os.path.isfile(each_path):
each_list = os.path.splitext(each)
if str(each_list) == '.txt':
file = open (each_path)
if word in file.read():
file.close()
print('=================================================')
print(f'在文件【{each_path}】中找到关键字【{word}】')
fun(each_path, word)
else:
next_path = each_path
find_fun(next_path, word)
def fun(each_path, word):
i = 0
count = []
file = open (each_path)
file_list = list(file)
for each_line in file_list:
i += 1
index = each_line.find(word)
if index != -1:
count.append(index)
for m in range(count[-1], len(each_line)):
if index != -1:
index = each_line.find(word, (count[-1] + 1), len(each_line))
print(f'关键字出现在第 {i} 行,第{count}位置')
count.clear()
file.close()
word = input('请将该脚本放于待查找的文件夹内,请输入关键字:')
path = os.getcwd()
print (f'请问是否需要打印关键字【{word}】在文件中的具体位置(YES\\NO):', end = '')
judge = input()
if judge == 'YES' or judge == 'yes':
find_fun(path, word)
已解决了,试过gbk 和 utf8 编码方式打开,都会报错
后来在群小伙伴的提示下发现我的目标文件有点是gbk编码 有的是utf8编码
这样就导致无论用哪种方式打开总会报编码错误的BUG
最后把所有文件全部修改为gbk编码方式就可以完美运行了
如果大家发现还有BUG请在后面跟帖讨论 sxhqyxc 发表于 2021-5-12 18:38
已解决了,试过gbk 和 utf8 编码方式打开,都会报错
后来在群小伙伴的提示下发现我的目标文件有点是gb ...
那你可以用chardetimport chardet
with open('test.txt', 'rb') as f:
cd = chardet.detect(f.read())['encoding']
with open('test.txt', 'r', encoding=cd) as f:
print(f.read())
页:
[1]