import os
files = os.listdir()
for file in files:
print(file, os.path.isdir(file))
结果输出:文件夹名称,False(不是文件夹) True(是文件夹)
推荐的使用方式
import os
for file in os.scandir():
print(file.name, file.path, file.is_dir())
结果输出的是:文件夹名称,路径和是否是文件夹的判断
编写一个python程序,示例文件夹内容如下,要求:
(1)找出当前目录下所有非文件夹的文件
(2)统计其中包含‘python'单词的文件数量
(3)不区分大小写,即大写和小写都包括在内
(4)输出文件数量
参考代码如下:
import os
os.chdir(r'D:\python_major\auto_office1')
ls_file = []
ls_dir = []
for file in os.scandir():
if file.is_dir():
ls_dir.append(file.name)
else:
ls_file.append(file.name)
print("文件夹的总量是{},\n文件为别为{}".format(len(ls_dir),ls_dir))
print('\n{}\n'.format('-'*30))
print("非文件夹的文件总量是{},\n文件为别为{}".format(len(ls_file),ls_file))
print('\n{}\n'.format('-'*30))
ls_python = []
for name in ls_file:
if ('python' in name) or('Python'in name):
ls_python.append(name)
print('含有python单词的文件数量有{}个,\n文件分别为{}'.format(len(ls_python),ls_python))