Discuss / Python / 作业2

作业2

Topic source

B O O M!

#1 Created at ... [Delete] [Delete and Lock User]

#!/usr/bin/env python3

# -*- coding:utf-8 -*-

# 编写一个程序,能在当前目录以及当前目录的所有子目录下查找文件名包含指定字符串的文件,并打印出相对路径。

import os, sys

from datetime import datetime

is_win32 = sys.platform == "win32"

dir_flag = "/"

if is_win32:

    dir_flag = "\\"

def find_files(dir, target_file_name):

    for file in os.listdir(dir):

        path = "%s%s%s" % (dir, dir_flag, file)

        if os.path.isdir(path):

            find_files(path, target_file_name)

        elif os.path.isfile(path):

            find_file_and_print(file, target_file_name)

def find_file_and_print(file, target_file_name):

    if str(file).find(target_file_name) >= 0:

        print(file)

def main():

    target_file_name = input("file:")

    if target_file_name == '':

        raise ValueError("请输入正确的目标查找文件名")

    path = os.path.abspath('.')

    find_files(path, target_file_name)

if __name__ == '__main__':

    main()


  • 1

Reply