JomQ 发表于 2020-4-4 19:13:18

请问第五行‘ext = os.path.splitext(each_file)[1]’里的【1】是什么意思?求指教~

import os

def search_file(start_dir, target) :
    os.chdir(start_dir)
   
    for each_file in os.listdir(os.curdir) :
      ext = os.path.splitext(each_file)
      if ext in target :
            vedio_list.append(os.getcwd() + os.sep + each_file + os.linesep) # 使用os.sep是程序更标准
      if os.path.isdir(each_file) :
            search_file(each_file, target) # 递归调用
            os.chdir(os.pardir) # 递归调用后切记返回上一层目录

start_dir = input('请输入待查找的初始目录:')
program_dir = os.getcwd()

target = ['.mp4', '.avi', '.rmvb']
vedio_list = []

search_file(start_dir, target)

f = open(program_dir + os.sep + 'vedioList.txt', 'w')
f.writelines(vedio_list)
f.close()

JomQ 发表于 2020-4-4 19:14:36

是读取第二个元素,也就是文件名后缀的意思吗

dlnb526 发表于 2020-4-4 19:14:45

本帖最后由 dlnb526 于 2020-4-4 19:15 编辑

os.path.splitext(each_file)取文件名
os.path.splitext(each_file)取扩展名
os.path.splitext(each_file) 返回文件名,扩展名元组
(文件名包含路径)

请学习‘索引’部分知识~

BngThea 发表于 2020-4-4 19:20:18

split返回一个列表,就是取第二个元素

qiuyouzhi 发表于 2020-4-4 19:52:48

因为splitext会返回一个列表(split同理),
这里我们想获取第二个元素,就在后面加

zltzlt 发表于 2020-4-4 19:55:14

表示取列表的第二个元素。ext = os.path.splitext(each_file) 整句代码的意思就是取出 each_file 文件的扩展名并赋值给 ext 变量。
页: [1]
查看完整版本: 请问第五行‘ext = os.path.splitext(each_file)[1]’里的【1】是什么意思?求指教~