[课后作业] 第030讲:文件系统:介绍一个高大上的东西
import osdef print_pos(key_dict):
keys = key_dict.keys()
keys = sorted(keys) # 由于字典是无序的,我们这里对行数进行排序
for each_key in keys:
print('关键字出现在第 %s 行,第 %s 个位置。' % (each_key, str(key_dict)))
def pos_in_line(line, key):
pos = []
begin = line.find(key)
while begin != -1:
pos.append(begin + 1) # 用户的角度是从1开始数
begin = line.find(key, begin+1) # 从下一个位置继续查找
return pos
def search_in_file(file_name, key):
f = open(file_name)
count = 0 # 记录行数
key_dict = dict() # 字典,用户存放key所在具体行数对应具体位置
for each_line in f:
count += 1
if key in each_line:
pos = pos_in_line(each_line, key) # key在每行对应的位置
key_dict = pos
f.close()
return key_dict
def search_files(key, detail):
all_files = os.walk(os.getcwd())
txt_files = []
for i in all_files:
for each_file in i:
if os.path.splitext(each_file) == '.txt': # 根据后缀判断是否文本文件
each_file = os.path.join(i, each_file)
txt_files.append(each_file)
for each_txt_file in txt_files:
key_dict = search_in_file(each_txt_file, key)
if key_dict:
print('================================================================')
print('在文件【%s】中找到关键字【%s】' % (each_txt_file, key))
if detail in ['YES', 'Yes', 'yes']:
print_pos(key_dict)
print(key_dict)
key = input('请将该脚本放于待查找的文件夹内,请输入关键字:')
detail = input('请问是否需要打印关键字【%s】在文件中的具体位置(YES/NO):' % key)
search_files(key, detail)
代码for each_file in i中的代表什么呢?
还有就是有没有这组代码的详细解读呢?
求大神帮忙!!!!!!! os.walk:遍历top路径以下所有的子目录,返回一个三元组:(路径, [包含目录], [包含文件])
i获取文件
解读的话后面的注释不是很清楚了吗 https://fishc.com.cn/forum.php?mod=viewthread&tid=181318&extra=page%3D1%26filter%3Dtypeid%26typeid%3D392
这里有大佬给了详细解读 疾风怪盗 发表于 2020-9-30 21:44
https://fishc.com.cn/forum.php?mod=viewthread&tid=181318&extra=page%3D1%26filter%3Dtypeid%26typeid%3 ...
啊这{:10_256:}
页:
[1]