为什么这个代码会说找不到文件?
#编写一个程序,用户输入关键字,查找当前文件夹内(如果当前文件夹内包含文件夹,则进入文件夹继续搜索)所有含有该关键字的文本文件(.txt后缀),要求显示该文件所在的位置以及关键字在文件中的具体位置(第几行第几个字符)
import os
key = input('请输入要查找的关键字:')
pos_dict = {} #记录关键字所在位置
pos = [] #记录关键字在每一行的具体位置
#遍历txt文件
all_file = os.walk(os.getcwd())
for each_file in all_file:
for ext_file in each_file:
if os.path.splitext(ext_file) == '.txt':
f = open(ext_file, encoding='utf-8')
count = 0 #记录关键字所在行数
pos.clear() #对于每一个文件清空列表
for each_line in f: #记录关键字的具体位置
if key in each_line:
count += 1
begin = each_line.find(key)
while begin != -1:
pos_dict = begin
begin = each_line.find(key,begin+1)
f.close()
key_list = pos_dict.keys()
key_list = sorted(key_list)# 由于字典是无序的,我们这里对行数进行排序
for each_key in key_list:
print('关键字出现在第 %s 行,第 %s 个位置。' % (each_key, str(pos_dict)))
为什么这个代码会说找不到文件?报错在14行
Traceback (most recent call last):
File "D:\系统\练习\作业.py", line 11, in <module>
f = open(ext_file, encoding='utf-8')
FileNotFoundError: No such file or directory: 'vedioList.txt' 路径不对呗 可能是文件权限不够 只有一个文件出现问题吗 错误提示:没有这样的文件或目录
要么把程序和需要搜索的文件放一起,要么改变路径
os.chdir(r"C:\Users\XXX\Desktop\temp") wp231957 发表于 2022-3-5 20:11
路径不对呗
但是我这个是对当前目录的文件的读取 本帖最后由 elven08 于 2022-3-5 22:09 编辑
那就是没有放到一起呗,我改了试了一下,这样可行
import os
key = input('请输入要查找的关键字:')
#os.chdir(r"C:\Users\tmj\Desktop\temp") #改变当前路径
#遍历txt文件
all_file = os.walk(os.getcwd())
for each_file in all_file:
for ext_file in each_file:
if os.path.splitext(ext_file) == '.txt':
f = open(ext_file, encoding='utf-8')
count = 0 #记录关键字所在行数
pos_file = {} #记录关键字所在文件名
pos_dict = {} #记录关键字所在位置
for each_line in f:
count += 1
if key in each_line:
begin = each_line.find(key)
while begin != -1:
pos_file = os.path.splitext(ext_file)
pos_dict = begin+1
begin = each_line.find(key,begin+1)
f.close()
key_list = pos_dict.keys()
for each_key in key_list:
print('关键字出现在 %s 文件,第 %s 行,第 %s 个位置。' % (pos_file,each_key, str(pos_dict))) 本帖最后由 elven08 于 2022-3-5 22:11 编辑
这个是测试结果 有错呢,会覆盖数据,你看一下吧,我也是新手,慢慢调试了改的
页:
[1]