给出指定的绝对路径,根据需要筛选的名称统计文件(非文件夹)数量。
import os
count = 0
files = os.listdir()
for file in files:
if bool(1 - os.path.isdir(file)):
if 'Python'.lower() in file.lower():
count += 1
print(file,os.path.abspath(file))
print('包含Python关键字的文件有:', count)
os.listdir()
返回的是一个list里面的值为当前路径下的文件名称,入参是一个路径,如果不传入则取当前运行python脚本的地址。os.path.isdir(file)
传入当前遍历的名称,判断是否是一个文件夹,如果是的话则返回True,不过我们这边是只去非文件夹所以bool(1 - False)取反。'Python'.lower() in file.lower()
这边我统计文件名包含Python字符的文件个数,由于忽略大小写则可以采用把所有转小写或者大写。in表示前者的字符是否在后者中包含。os.path.abspath(file)
输出当前文件路径。