您好,登錄后才能下訂單哦!
1.遞歸列出目錄里的文件的腳本舉例
列出目錄中的文件可以通過下面方法:os.listdir()
In [1]: import os
In [4]: os.listdir('/root')
Out[4]:
['.tcshrc',
'.bash_history',
'.bashrc',
'ENV',
'.cache',
'.config',
'.cshrc',
'.bash_logout',
'python',
'.ssh',
'shell',
'.bash_profile',
'.ipython',
'.viminfo',
'dictionary.txt',
'1.txt']
判斷是否為目錄:
In [5]: os.path.isdir('/home')
Out[5]: True
判斷是否為文件:
In [7]: os.path.isfile('/etc/rc.local')
Out[7]: True
拼接文件名字的絕對(duì)路徑:
In [8]: os.path.join('/etc/','passwd','abc')
Out[8]: '/etc/passwd/abc'
列出目錄下所有文件腳本如果下:
#!/usr/bin/env python
#FengXiaoqing
# listDir.py
import os
import sys
def print_files(path):
lsdir = os.listdir(path)
dirs = [i for i in lsdir if os.path.isdir(os.path.join(path,i))]
files = [i for i in lsdir if os.path.isfile(os.path.join(path,i))]
if dirs:
for d in dirs:
print_files(os.path.join(path,d))
if files:
for f in files:
print (os.path.join(path,f))
print_files(sys.argv[1])
[root@localhost ~]# tree /tmp
/tmp
├── 123.tx
├── 123.txx
└── a
└── b
├── b.txt
└── c
├── c.txt
└── d
└── d.txt
4 directories, 5 files
[root@localhost ~]#
[root@localhost ~]# python listDir.py /tmp
/tmp/123.tx
/tmp/123.txx
/tmp/a/b/b.txt
/tmp/a/b/c/c.txt
/tmp/a/b/c/d/d.txt
[root@localhost ~]#
lambda函數(shù)是一種快速定義單選的最小函數(shù),可以用在任何需要函數(shù)的地方。
3*5實(shí)現(xiàn)方法:
In [1]: def fun(x,y):
...: return x * y
...:
In [2]: fun(3,5)
Out[2]: 15
匿名函數(shù)定義如果下:
In [3]: lambda x,y:x * y
Out[3]: <function __main__.<lambda>> #返回的對(duì)象
In [4]: r = lambda x,y:x * y
In [6]: r(3,5)
Out[6]: 15
匿名函數(shù)優(yōu)點(diǎn):
1.使用python寫一些腳本時(shí)候,使用lambda可以省去定義函數(shù)的過程,讓代碼更加精簡(jiǎn)。
2.對(duì)于一些抽象的,不會(huì)被別的地方再重復(fù)使用的函數(shù),有時(shí)候函數(shù)起個(gè)名字也是個(gè)難題,使用lambda不需要層次理論考慮命名的問題。
3.使用lambda在某些時(shí)候讓代碼更容易理解。
lambda基礎(chǔ):
lambda語(yǔ)句中,冒號(hào)前是參數(shù),可以有多個(gè),逗號(hào)隔開,冒號(hào)右邊是返回值。
lambda語(yǔ)句構(gòu)建的其實(shí)是一個(gè)函數(shù)對(duì)象。
help(reduce)
Help on built-in function reduce in module __builtin__:
reduce(...)
reduce(function, sequence[, initial]) -> value
Apply a function of two arguments cumulatively to the items of a sequence,
from left to right, so as to reduce the sequence to a single value.
For example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates
((((1+2)+3)+4)+5). If initial is present, it is placed before the items
of the sequence in the calculation, and serves as a default when the
sequence is empty.
(END)
reduce二元計(jì)算:
In [19]: def add(x,y):
return x + y
....:
In [20]: add(1,3)
Out[20]: 4
求1到100相加的和:
#!/usr/bin/python
# -*- coding: utf-8 -*-
#date:2019.07.05
print ('1+100的總和是:%s' % reduce(lambda x,y:x+y,range(1,101)))
求階乘:
#!/usr/bin/python
# -*- coding: utf-8 -*-
#date:2019.07.05
print ('5的階乘是:%s' % reduce(lambda x,y:x*y,range(1,6)))
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。