根据文件属性查找文件

-文件的属性

1.os.path.getsize

2.os.path.isfile()

3.os.stat

-文件后缀名

1. split

2.[-3:]

3. re

4. endswith

import os
os.chdir(r'D:\全栈\第二模块第二次作业')
os.getcwd()
'D:\\全栈\\第二模块第二次作业'
filename1 = r'D:\全栈\第二模块第二次作业\bwl.py'
os.path.getsize(filename1)
4697
os.path.isfile('a')
False
os.path.isfile('bwl.py')
True
os.stat('bwl.py')
os.stat_result(st_mode=33206, st_ino=286260051314738315, st_dev=3490529842, st_nlink=1, st_uid=0, st_gid=0, st_size=4697, st_atime=1530543099, st_mtime=1530707793, st_ctime=1530538739)
filename1[-3:]
'.py'
os.path.splitext(filename1)
('D:\\全栈\\第二模块第二次作业\\bwl', '.py')
filename1.endswith('py')
True
#######################
os.listdir()
['0202zhaofangtao.zip',
 '21dian.py',
 'beiwanglu.py',
 'beiwanglu1.py',
 'bwl.py',
 'color_me.py',
 'transfer.py',
 'transfer2.py',
 'transfer3.py',
 'transfer4.py',
 'zz.py',
 '新建 Microsoft Excel 工作表.xlsx',
 '新建文件夹',
 '新建文本文档 - 副本 (2).pdf',
 '新建文本文档 - 副本 (3).doc',
 '新建文本文档 - 副本 (4).html',
 '新建文本文档 - 副本.xlsx',
 '新建文本文档.txt']
filename2 = r'D:\全栈\第二模块第二次作业\zz.py'
import re
re_filename = re.compile('(.*pdf$)|(.*doc$)|(.*html$)|(.*py$)')
re_filename.match(filename2).group()  # 感觉鸡肋
'D:\\全栈\\第二模块第二次作业\\zz.py'
os.walk('.')
<generator object walk at 0x000002721AC09E60>
os.walk?
Signature: os.walk(top, topdown=True, onerror=None, followlinks=False)
Docstring:
Directory tree generator.

For each directory in the directory tree rooted at top (including top
itself, but excluding '.' and '..'), yields a 3-tuple

    dirpath, dirnames, filenames
  File "<ipython-input-31-0b1889725fcb>", line 3
    Docstring:
              ^
SyntaxError: invalid syntax
for root, dirs, files in os.walk('.'):

    print(root)  # 根目录 .
    print()
    print(dirs)  # 根目录下的子目录 如:新建文件夹
    print()
    print(files)  # 目录中的文件
    print()
#     print(root, dirs, files)
.

['新建文件夹']

['0202zhaofangtao.zip', '21dian.py', 'beiwanglu.py', 'beiwanglu1.py', 'bwl.py', 'color_me.py', 'transfer.py', 'transfer2.py', 'transfer3.py', 'transfer4.py', 'zz.py', '新建 Microsoft Excel 工作表.xlsx', '新建文本文档 - 副本 (2).pdf', '新建文本文档 - 副本 (3).doc', '新建文本文档 - 副本 (4).html', '新建文本文档 - 副本.xlsx', '新建文本文档.txt']

.\新建文件夹

[]

['bwl1.py', 'db.pkl', 'transfer5.py']
# os.walk 便利目录,找到对应后缀名,并大小小于1M的文件
for root, dirs, files in os.walk('.'):
#     print(root, dirs, files)
    for name in files:
        file = os.path.join(root, name)  # 拼接目录,当前目录下的文件
        if re_filename.match(file) and os.path.getsize(file) < 1024 * 1024 * 1024 * 1024:
            print(name)
21dian.py
beiwanglu.py
beiwanglu1.py
bwl.py
color_me.py
transfer.py
transfer2.py
transfer3.py
transfer4.py
zz.py
新建文本文档 - 副本 (2).pdf
新建文本文档 - 副本 (3).doc
新建文本文档 - 副本 (4).html
bwl1.py
transfer5.py

猜你喜欢

转载自blog.51cto.com/13118411/2136872