Python小程序(4)检查文件与文件夹

Doubi Gao3 posted @ 2014年4月02日 10:53 in Language with tags python , 971 阅读

Python中提供了很多这样的函数:返回有关文件系统中文件与文件夹信息。

常见的有:os.listdir(p),os.getcwd(),os.isfile(p),os.isdir(p),os.stat(fname)

其中cwd的英文全称是:current working directory,即当前工作目录的意思。

os.stat返回的是fname的信息,如最后一次修改时间,大小等。

listdir,isfile,isdir,望文生义,既知道是列出指定文件夹p中所有文件和文件夹的名称,isfile(p),isdir(p)则是判断p是否为单一文件或者是文件夹。

 

import os

def list_cwd():
    """ Return current working directory
"""
    return os.listdir(os.getcwd())

def files_cwd():
    """ Return files
"""
    return [p for p in list_cwd() if os.path.isfile(p)]

def folders_cwd():
    """ Return folders
"""
    return [p for p in list_cwd() if os.path.isdir(p)]

def list_py(path = None):
    """ Return the files if it's endswith '.py'
"""
    if(path == None):
        path =os.getcwd()
        return [fname for fname in os.listdir(path)
        if os.path.isfile(fname)
        if fname.endswith('.py')]
    
def size_in_bytes(fname):
    """ Return the size of a file
"""
    return os.stat(fname).st_size

def cwd_size_in_bytes():
    """ Return the total sizes of files
"""
    total = 0
    for name in files_cwd():
        total += size_in_bytes(name)
    return total
jackjohnny 说:
2021年6月26日 21:37

I was surfing the Internet for information and came across your blog. I am impressed by the information you have on this blog. It shows how well you understand this subject. 안전놀이터

jackjohnny 说:
2021年6月29日 18:16

If more people that write articles really concerned themselves with writing great content like you, more readers would be interested in their writings. Thank you for caring about your content. indian visa

jackjohnny 说:
2021年6月29日 18:18

If more people that write articles really concerned themselves with writing great content like you, more readers would be interested in their writings. Thank you for caring about your content. indian visa

jackjohnny 说:
2021年7月05日 18:47

This is my first time i visit here. I found so many interesting stuff in your blog especially its discussion. From the tons of comments on your articles, I guess I am not the only one having all the enjoyment here keep up the good work สล็อต

jackjohnny 说:
2021年7月11日 17:42

I like your post. It is good to see you verbalize from the heart and clarity on this important subject can be easily observed... 토토사이트


登录 *


loading captcha image...
(输入验证码)
or Ctrl+Enter