解答第0题:
import os
dict1 = dict()
style = []
all = os.listdir()
#print(all)
dict1['dir'] = 0
for i in all:
if os.path.isdir(i):
dict1['dir'] += 1
else:
a = os.path.splitext(i)[1]
if a not in style:
style.append(a)
dict1[a] = 1
else:
dict1[a] += 1
print(style) #['.txt', '.docx', '.png', '.pkl', '.py']
print(dict1) #{'dir': 2, '.txt': 2, '.docx': 1, '.png': 1, '.pkl': 2, '.py': 1}
解答第1题:
dict1 = dict()
all = os.listdir()
# print(all)
for i in all:
if os.path.isfile(i):
dict1[i] = os.path.getsize(i)
print(dict1)
#{'1.txt': 9, '2.txt': 6, '3.docx': 0, '4.png': 0, '5.pkl': 0, '6.pkl': 0, 'P82.py': 618}
解答第2题:
image.png
fold = "D:\\工作\\201804_学习\\Python\\小甲鱼\\P8\\2-OS"
filename = "test.txt"
def search(fold, filename):
os.chdir(fold)
all = os.listdir()
if os.path.exists(filename):
print(fold + os.sep + filename)
for i in all:
if os.path.isdir(i):
fold1 = os.path.join(fold, i)
search(fold1, filename)
search(fold,filename)
image.png
解答第3题:
fold = "D:\\工作\\201804_学习\\Python\\小甲鱼\\P8\\2-OS"
def search(fold,move):
os.chdir(fold)
all = os.listdir()
for i in all:
if os.path.splitext(i)[1] in move:
filelist.append(fold + os.sep + i)
# print(fold + os.sep + i)
if os.path.isdir(i):
fold1 = os.path.join(fold, i)
search(fold1, move)
os.chdir(fold)
return filelist
move = [".mp4",".rmvb",".avi"]
filelist = []
a = search(fold,move)
print(a)
image.png
网友评论