python代码求优化
代码目的是找出对应类型的文件,可结果里会有不相干的文件名,甚至有名字不相干的目录名import os
def file_find(dir_position, suffix):
os.chdir(dir_position)
all_files = os.listdir(os.curdir)
for each_file in all_files:
if os.path.splitext(each_file) in suffix:
viewlist.append(os.getcwd() + os.sep + each_file + '\n')
if os.path.isdir(each_file):
file_find(each_file, suffix)
os.chdir(os.pardir)
dir_position = input('请输入路径:')
suffix = input('请输入要查找的文件类型(.txt):')
viewlist = []
file_find(dir_position, suffix)
f = open(dir_position + os.sep + 'viewlist.txt', 'w')
f.writelines(viewlist)
f.close()
圈出来的是目录,而且名字都没有关系,为什么会打印出来{:10_249:}
file:///C:/Users/123/Desktop/Inked%E6%8D%95%E8%8E%B7_LI.jpg 怎么发图片啊 新人发图三件套 官方教程 图壳 图桌 本帖最后由 blahblahfc 于 2021-9-14 12:12 编辑
可能是第8行:
if os.path.splitext(each_file) in suffix:
无后缀文件或文件夹时 os.path.splitext(each_file) 返回空字符串 '',
导致 if 条件 '' in suffix 一直为真,suffix 的值是字符串
os.path.splitext('foo')
# 返回 ('foo', '') import os
def file_find(dir_position, suffix):
os.chdir(dir_position)
all_files = os.listdir(os.curdir)
for each_file in all_files:
if os.path.isdir(each_file):
file_find(each_file, suffix)
os.chdir(os.pardir)
else:
if os.path.splitext(each_file) in suffix:
viewlist.append(os.getcwd() + os.sep + each_file + '\n')
dir_position = input('请输入路径:')
suffix = input('请输入要查找的文件类型(.txt):')
viewlist = []
file_find(dir_position, suffix)
f = open(dir_position + os.sep + 'viewlist.txt', 'w', encoding="utf-8")
f.writelines(viewlist)
f.close()
你那样的逻辑会一些问题,我也很难说清楚
一般我用的逻辑是if 是否为文件夹:
xxx
else:
if 是否满足要求:
xxxx 大马强 发表于 2021-9-14 12:18
你那样的逻辑会一些问题,我也很难说清楚
一般我用的逻辑是
因为不是文件夹,就是一个文件,所以用if else 搭配就不用两次判断 大马强 发表于 2021-9-14 12:04
新人发图三件套 官方教程 图壳 图桌
感谢{:5_109:}
页:
[1]