jzztf / wiki

wiki
https://jzztf.github.io
Other
1 stars 0 forks source link

python-files-direction-manage #34

Open jzztf opened 6 years ago

jzztf commented 6 years ago

python 文件及目录管理

查看目录

>>> import os
>>> os.getcwd()
'/home/ztf'
>>> os.chdir('/tmp')
>>> os.getcwd()
'/tmp'
>>> os.path.split('/tmp/test.sh')
('/tmp', 'test.sh')
>>> (dirname,filename) = os.path.split('/tmp/test.sh')
>>> print(dirname)
/tmp
>>> print(filename)
test.sh
>>> os.path.join(dirname,filename)
'/tmp/test.sh'
>>> os.path.splitext('/tmp/test.sh')
('/tmp/test', '.sh')
>>> os.path.splitext(filename)
('test', '.sh')
>>> (shortname,extension) = os.path.splitext(filename)
>>> print(shortname)
test
>>> print(extension)
.sh

glob模块

可以根据通配符返回当前目录下的文件及目录

>>> import glob
>>> glob.glob('tmp/*.sh')
['tmp/loop.sh', 'tmp/test.sh']
>>> for i in glob.glob('tmp/*.sh'):
...     print(i)
... 
tmp/loop.sh
tmp/test.sh