Python目录是计算机语言常用的语言,可是很多人还是对其不太了解,觉得它的实际应用语言操作太难,其实如果你了解了Python目录的操作技能,你对其就有个更深的了解。你如果感兴趣的话,就看看下面的文章吧!
和普通文件一样,关于Python目录的操作也很容易掌握。首先,列出一个目录的内容:
view plaincopy to clipboardprint?
import os
for fileName in os.listdir ( '/' ):
print fileName
import os
for fileName in os.listdir ( '/' ):
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
print fileName正如你所见,这很简单,用三行代码就可以完成。
创建目录也很简单:
view plaincopy to clipboardprint?
import os
for fileName in os.listdir ( '/' ):
print fileName
import os
for fileName in os.listdir ( '/' ):
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
删除刚才创建的Python目录:也可以创建多级目录:
view plaincopy to clipboardprint?
import os
os.makedirs ( 'I/will/show/you/how/deep/the/rabbit/hole/goes' )
import os
os.makedirs ( 'I/will/show/you/how/deep/the/rabbit/hole/goes' )
- 1.
- 2.
- 3.
- 4.
- 5.
如果没有在创建的文件夹中添加任何东西,就可以一次性将它们全部删除(即,删除所列的所有空文件夹):
view plaincopy to clipboardprint?
import os
os.removedirs( 'I/will/show/you/how/deep/the/rabbit/hole/goes' )
import os
os.removedirs ( 'I/will/show/you/how/deep/the/rabbit/hole/goes' )
- 1.
- 2.
- 3.
- 4.
- 5.
当需要对一个特定的文件类型进行操作时,我们可以选择“fnmatch”模块。以下是显示“.txt”文件的内容和“.exe”文件的文件名:
view plaincopy to clipboardprint?
import fnmatch
import os
for fileName in os.listdir ( '/' ):
if fnmatch.fnmath ( fileName, '*.txt' ):
print open ( fileName ).read()
elif fnmatch.fnmatch ( fileName, '*.exe' ):
print fileName
import fnmatch
import os
for fileName in os.listdir ( '/' ):
if fnmatch.fnmath ( fileName, '*.txt' ):
print open ( fileName ).read()
elif fnmatch.fnmatch ( fileName, '*.exe' ):
print fileName“*”
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
- 10.
- 11.
- 12.
- 13.
- 14.
- 15.
字符可以表示任意长度的字符。如果要匹配一个字符,则使用“?”符号:
view plaincopy to clipboardprint?
import fnmatch
import os
for fileName in os.listdir ( '/' ):
if fnmatch.fnmatch ( fileName, '?.txt' ):
print 'Text file.'
import fnmatch
import os
for fileName in os.listdir ( '/' ):
if fnmatch.fnmatch ( fileName, '?.txt' ):
print 'Text file.'“fnmatch”
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
- 10.
- 11.
以上就是对关于Python目录具体操作内容的简介。
【编辑推荐】