Discuss / Python / 交作业1:

交作业1:

Topic source

明天过后.

#1 Created at ... [Delete] [Delete and Lock User]

没实现获取剩余空间大小

import os, time
demopath = r'C:/Users/rog/Desktop/Demo'

def dir_l(path):
    filenum, filesize, dirnum = 0, 0, 0
    for i in os.listdir(path):
        i = os.path.join(path, i)
        #os.listdir(i)只会列出i下的文件和目录名称,因此要用os.path.join(a,b,c)把a,b,c连接在一起返回绝对路径
        mtime = time.strftime("%Y-%m-%d  %H:%M", time.localtime(os.path.getmtime(i)))
        #os.path.getmtime(name) 获得name文件的最后修改的时间(时间戳)
        #time.localtime() 将Timestamp对象转换为struct_time对象
        #strftime()将struct_time对象转换为格式化时间
        if os.path.isfile(i):
            size = os.path.getsize(i)
            print('%s\t\t%d\t%s' %(mtime, size, i))
            filenum += 1
            filesize += size
        if os.path.isdir(i):
            print('%s\t<DIR>\t%s' %(mtime, i))
            dirnum += 1
    print('\t\t%d个文件\t%d个字节' %(filenum, filesize))
    print('\t\t%d个目录' %dirnum)

if __name__ == '__main__':
    dir_l(demopath)

明天过后.

#2 Created at ... [Delete] [Delete and Lock User]

交作业二:

没返回相对路径,返回的绝对路径。

import os
demopath = r'C:/Users/rog/Desktop/Demo'

def search(text, path):
    if not isinstance(text, str):
        raise TypeError('Please input str')
    for name in os.listdir(path):
        abs_path = os.path.join(path, name)
        if os.path.isdir(abs_path):
            search(text, abs_path)
        else:
            if name.find(text) != -1:
                print(name,'\t',demopath)

if __name__ == '__main__':
    search('Demo', demopath)

明天过后.

#3 Created at ... [Delete] [Delete and Lock User]

demopath改成abs_path

明天过后.

#4 Created at ... [Delete] [Delete and Lock User]

重交作业二:用了os.walk返回的相对路径

import os

def search_files_with_text(text, path):
    if not isinstance(text, str):
        raise TypeError('Please input str')
    for root, dirs, files in os.walk(path):
        for name in files:
            if text in name:
                print(name, '\t', os.path.relpath(os.path.join(root, name), path))

if __name__ == '__main__':
    search_files_with_text('Demo2', '.')

juven永恒

#5 Created at ... [Delete] [Delete and Lock User]

这个好, 简单明了


  • 1

Reply