需求:编写一个程序,用户输入开始搜索的路径,查找该路径下(包含子文件夹内)所有的视频格式文件(要求查找MP4、rmvb、avi的格式即可),并创建一个文件(videoList.txt)存放所有找到的文件的路径。
# -*- coding: utf-8 -*-
import os
def search_file(start_dir):
os.chdir(start_dir) #os.chdir() 方法用于改变当前工作目录到指定的路径。
for each_file in os.listdir(os.curdir):
# print (each_file)
if os.path.splitext(each_file)[1] in [".mp4",".rmvb",".avi"]:
# print (os.getcwd()+os.sep+each_file+os.linesep)
txt_write(os.getcwd()+os.sep+each_file+os.linesep)
#os.linesep字符串给出当前平台使用的行终止符。例如,Windows使用'\r',Linux使用''而Mac使用'\r'。
if os.path.isdir(each_file):
search_file(each_file) #递归调用
os.chdir(os.pardir) # 切换到上级目录 递归调用后,切记返回上一层目录
def txt_write(content):
file_write=open("E:\\Python Program\\videoList.txt","a")
print (content,file=file_write)
file_write.close()
start_dir=input(r"请输入待查找的初始目录:")
search_file(start_dir)