鱼C论坛

 找回密码
 立即注册
查看: 1995|回复: 2

[已解决]求助一道python作业~

[复制链接]
发表于 2020-12-1 13:56:50 | 显示全部楼层    本楼为最佳答案   
你把问题想复杂了。直接在get_targets函数的if下添加上打开文件、读取文件,判断文件每行首字母即可,其他的不用动。
is_decoy使用递归多累啊,直接一个循环搞定。
  1. import os
  2. def is_decoy(lines):
  3.     if not lines:
  4.         return False
  5.     for line in lines:
  6.         if line[0] in ['A','C','M','E']:
  7.             return True
  8.     return False
  9. def get_targets(path):
  10.     for file in os.listdir(path):
  11.         if os.path.isfile(path+'/'+file):
  12.             thisfile=open(path+os.sep+file,'r')
  13.             filelines=thisfile.readlines()
  14.             thisfile.close()
  15.             if is_decoy(filelines):
  16.                 print(path+'/'+file)  #This is a file, print out the path
  17.         else:
  18.             get_targets(path+'/'+file)  #Go into a subdirectory
复制代码
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 1 反对 0

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2025-10-5 04:35

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表