Discuss / Python / 太笨了,写了半天。写Java习惯了,不会用这种仅支持值传递的静态参数的了QAQ。求更好的写法。

太笨了,写了半天。写Java习惯了,不会用这种仅支持值传递的静态参数的了QAQ。求更好的写法。

Topic source
import os
import re


# 作业:编写一个程序,能在当前目录以及当前目录的所有子目录下查找文件名包含指定字符串的文件,并打印出相对路径。
path = out_path = '.'
file_str = input('Please enter the string you want to look for: ')


def look_up(path):
    global out_path

    for p in os.listdir(path):
        out_path = os.path.join(out_path, p)
        if os.path.isdir(p): 
            look_up(p)
        else: 
            file_name = os.path.splitext(p)[0]
            if match_string(file_name, file_str):
                print(out_path)
        out_path = os.path.split(out_path)[0] 
        continue


def match_string(file, str):
    if re.match('.*'+ str +'.*', file): 
        return True
    else: 
        return False


look_up(path)

写错了!!!改成这样:

import os
import re


# 作业:编写一个程序,能在当前目录以及当前目录的所有子目录下查找文件名包含指定字符串的文件,并打印出相对路径。
path = out_path = '.'
file_str = input('Please enter the string you want to look for: ')


def look_up(path):
    global out_path

    for p in os.listdir(path):
        out_path = os.path.join(out_path, p)
        if os.path.isdir(out_path): 
            look_up(out_path)
        else: 
            file_name = os.path.splitext(p)[0]
            if match_string(file_name, file_str):
                print(out_path)
        out_path = os.path.split(out_path)[0] 
        continue


def match_string(file, str):
    if re.match('.*'+ str +'.*', file): 
        return True
    else: 
        return False

look_up(path)

  • 1

Reply