Discuss / Python / 第二题

第二题

Topic source
# -*- coding: utf-8 -*-
import os
def select(fileName,path = ''):
    _list = [x for x in (os.listdir('.') if path == '' else os.listdir(path))]
    for _file in _list:
        if os.path.isfile(os.path.join(path,_file)):
            if fileName in _file:
                print _file
        elif os.path.isdir(os.path.join(path,_file)):
            select(fileName,os.path.join(path,_file))

select('test')

无愠无殇

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

小范围的修改,还有个问题,return 'Done'时,总是提示

File "D:/Python34/Code/demo3.py", line 12 return 'Done' ^ TabError: inconsistent use of tabs and spaces in indentation

查看过,不是tab 跟空格的混用问题

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

import os
def select(fileName,path = '.'):
    _list = [x for x in os.listdir(path)]
    for _file in _list:
        if os.path.isfile(os.path.join(path,_file)):
            if fileName in _file:
                print(_file,'相对路径',path)
        elif os.path.isdir(os.path.join(path,_file)):
            select(fileName,os.path.join(path,_file))
    # return 'Done'

print(select('de'))

无愠无殇

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

我靠。。。。真是tab 问题。。

redglass2015

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

为什么直接用os.path.isfile(-file)不可以? [x for x in os.listdir('.') if os.path.isdir(x)]这个里面不是直接用的吗??

没看懂,老师帮忙讲一下思路吧

listdir只是获取指定目录下的所有文件而并非全目录,所以需要用join补全路径再去判断是文件还是文件夹


  • 1

Reply