Discuss / Python / 打卡第八天

打卡第八天

Topic source

皆由唧唧

#1 Created at ... [Delete] [Delete and Lock User]
import os
import sys

def dir_l():
    print(os.system('pwd'))
    print(os.system('ls -l | grep "^d"'))

if sys.argv[1] == 'dir -l':
    dir_l()

皆由唧唧

#2 Created at ... [Delete] [Delete and Lock User]
#!/usr/bin/env python3

import os


def findDir(d):# 返回目录下所有的子目录及子子子...目录,传递列表,返回列表
    for m in d:
        os.chdir(m)
        dir_list = [x for x in os.listdir('.') if os.path.isdir(x)]
        for n in dir_list:
            d.append(os.path.join(m,n))
    return d

def findFile(s,d):# 返回所有目录下的文件名包含字符串s的文件
    L = []
    for n in d:
        os.chdir(n)
        files = [x for x in os.listdir('.') if os.path.isfile(x)]
        for f in files:
            if len(f) > len(s):
                for i in range(len(f)-len(s)):
                    ss = f[i:i+len(s)]
                    if ss == s:
                        L.append(os.path.join(n,f))
                        break
            if f == s:
                L.append(os.path.join(n,f))
    for i in L:
        print(i)

def find_s_file(s,d):
    findDir(d)
    findFile(s,d)

d = [os.path.abspath('.')]
s = input('Enter one string: ')
find_s_file(s,d)

皆由唧唧

#3 Created at ... [Delete] [Delete and Lock User]
#!/usr/bin/env python3

import os


def findDir(d):# 返回目录下所有的子目录及子子子...目录,传递列表,返回列表
    for m in d:
        os.chdir(m)
        dir_list = [x for x in os.listdir('.') if os.path.isdir(x)]
        for n in dir_list:
            d.append(os.path.join(m,n))
    return d

def findFile(s,d):# 返回所有目录下的文件名包含字符串s的文件
    L = []
    for n in d:
        os.chdir(n)
        files = [x for x in os.listdir('.') if os.path.isfile(x)]
        for f in files:
            if s in f:
                L.append(os.path.join(n,f))
    for i in L:
        print(i)

def find_s_file(s,d):
    findDir(d)
    findFile(s,d)

d = [os.path.abspath('.')]
s = input('Enter one string: ')
find_s_file(s,d)

皆由唧唧

#4 Created at ... [Delete] [Delete and Lock User]
#!/usr/bin/env python3
# -*- coding:utf-8 -*-

import os

def find_s_file(d, s):
    os.chdir(d)
    for m in os.listdir('.'):
        n = os.path.join(d, m)
        if os.path.isfile(n) and s in n:
            print(n)
        if os.path.isdir(n):
            find_s_file(n, s)

s = input('Enter one string: ')
d = os.path.abspath('.')

find_s_file(d, s)

测试了一下你的,最后得到的是绝对路径,题目是要查找文件名包含指定字符串的文件,但是你的是查找的是绝对路径而不是文件名


  • 1

Reply