zoukankan      html  css  js  c++  java
  • Python之OS(系统操作)模块常用函数

    mkdir(path[, mode=0777])

    makedirs(name,mode=511)

    rmdir(path)

    removedirs(path)

    listdir(path)

    getcwd()

    chdir(path)

    walk(top, topdown=True, onerror=None)  返回一个元组:(遍历的路径,目录,文件列表)


    我们来遍历一下文件:

     1 >>> for path, dir, filename in os.walk('/home/branches/python/testdir'):
     2 ...     for filen in filename:
     3 ...             os.path.join(path, filen)
     4 ... 
     5 '/home/branches/python/testdir/f1'
     6 '/home/branches/python/testdir/f2'
     7 '/home/branches/python/testdir/f3'
     8 '/home/branches/python/testdir/jpg/0.ipg'
     9 '/home/branches/python/testdir/jpg/3.ipg'
    10 '/home/branches/python/testdir/jpg/2.ipg'
    11 '/home/branches/python/testdir/jpg/1.ipg'
    12 '/home/branches/python/testdir/jpg/get_img.py'
    13 >>> 
    14 >>> 
    15 >>> 
    16 >>> for path, dir, filename in os.walk('testdir'):
    17 ...     for filen in filename:
    18 ...             os.path.join(path, filen)
    19 ... 
    20 'testdir/f1'
    21 'testdir/f2'
    22 'testdir/f3'
    23 'testdir/jpg/0.ipg'
    24 'testdir/jpg/3.ipg'
    25 'testdir/jpg/2.ipg'
    26 'testdir/jpg/1.ipg'
    27 'testdir/jpg/get_img.py'
    28 >>> 
     1 #!/usr/bin/python
     2 #coding:utf8
     3 
     4 import os
     5 
     6 def dirList(path):      # 列出当前目录下的完整路径名
     7         filelist = os.listdir(path)
     8         # fpath = os.getcwd()   # 它获取的是程序所在路径
     9         allfile = []
    10         for filename in filelist:
    11                 # allfile.append(fpath  + '/' + filename)
    12                 filepath = os.path.join(path, filename) # 用os模块的方法进行路径拼接
    13                 if os.path.isdir(filepath):
    14                         dirList(filepath)
    15                 print filepath  
    16 
    17 allfile = dirList('/home/branches/python/testdir')
  • 相关阅读:
    网络编程-python实现-UDP(1.1.2)
    网络编程-python实现-socket(1.1.1)
    1-浮动布局
    1-解决java Scanner出现 java.util.NoSuchElementException
    1.激活函数
    A-交叉熵的使用
    matplotlib的学习16-animation动画
    matplotlib的学习15-次坐标轴
    matplotlib的学习14-图中图
    07-爬虫验证码破解实战
  • 原文地址:https://www.cnblogs.com/fallenmoon/p/6994899.html
Copyright © 2011-2022 走看看