-文件的属性1.os.path.getsize2.os.path.isfile()3.os.stat-文件后缀名1. split2.[-3:]3. re4. 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 rere_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 topitself, 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.pybeiwanglu.pybeiwanglu1.pybwl.pycolor_me.pytransfer.pytransfer2.pytransfer3.pytransfer4.pyzz.py新建文本文档 - 副本 (2).pdf新建文本文档 - 副本 (3).doc新建文本文档 - 副本 (4).htmlbwl1.pytransfer5.py