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

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

Python小程序(3)之字典的使用

Python中字典感觉和C++中的map差不多嘛。当单位插入到字典中时,顺序可能会改变,应是根据键的字典序来排列的。

字典就那么几个函数,如:

d.pop(); d.items(); d.values(); d.keys(); d.copy();d.clear(); d.update(e); (e是键-值类型)

个人认为d.items(); d.get(key); d.update(e); d.pop(); d.copy();d.clear()比较重要,记住几个常用的就行了。

 

import re

def main():
    color = {'red':1, 'blue':2, 'gress':3, 'orange':4}
    map = color.copy()
    print('color:', color)
    print('map:', map)
    
    lst = []
    k = color.values()
    for i in k:
        print('values:', i, end = ' ')
        if i >= 1:
            lst.append(i)
    print('\nlst:', lst)
    print('\n')

    map.clear()
    color.clear()
####################################################
    
    map = {6:'red', 5:'blue', 4:'gress', 3:'orange', 2:'gresssss!', 1:'gressss!!'}
    color = map.copy()
    print('color:', color)
    print('map:', map)
    
    result = []
    k = map.items()
    for i in k:
        print('items:', i, end = ' ')
        d = re.match('gress', i[1])
        if d:
            result.append(i[1])
    print('\nresult:', result)

    map.clear()
    color.clear()

The Zen of Python

在Python3.x中输入import this就出现以下内容:直译为Python的禅宗,即Python之禅。

The Zen of Python, by Tim Peters

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!

优美胜于丑陋(Python 以编写优美的代码为目标)
明了胜于晦涩(优美的代码应当是明了的,命名规范,风格相似)
简洁胜于复杂(优美的代码应当是简洁的,不要有复杂的内部实现)
复杂胜于凌乱(如果复杂不可避免,那代码间也不能有难懂的关系,要保持接口简洁)
扁平胜于嵌套(优美的代码应当是扁平的,不能有太多的嵌套)
间隔胜于紧凑(优美的代码有适当的间隔,不要奢望一行代码解决问题)
可读性很重要(优美的代码是可读的)
即便假借特例的实用性之名,也不可违背这些规则(这些规则至高无上)
不要包容所有错误,除非你确定需要这样做(精准地捕获异常,不写 except:pass 风格的代码)
当存在多种可能,不要尝试去猜测
而是尽量找一种,最好是唯一一种明显的解决方案(如果不确定,就用穷举法)
虽然这并不容易,因为你不是 Python 之父(这里的 Dutch 是指 Guido )
做也许好过不做,但不假思索就动手还不如不做(动手之前要细思量)
如果你无法向人描述你的方案,那肯定不是一个好方案;反之亦然(方案测评标准)
命名空间是一种绝妙的理念,我们应当多加利用(倡导与号召)

Python小程序(2)

python函数,有关默认函数的一个要点是,函数可根据需要使用任意数量的默认参数,但带默认值的参数不能位于没有默认值的参数前面。

比如说:

 

def greet(name, greeting = 'Hello '):
    print(greeting + name+'!')

#def greet(greeting = 'Hello', name):
#    print(greeting, name+'!')

Python小程序(1)

偷闲学了以下Python,Python中对缩进要求很特别严,for if else while后面接的都是:

我用的是python3.1,下载地址在传送门

n = int(input('Enter an interger >=0 : '))
fact = 1
for i in range(n):
    fact = fact*(i+1)
print(str(n)+ ' factorial is ' + str(fact))