python os模块主要函数

使用python提供的os模块,对文件和目录进行操作,重命名文件,添加,删除,复制目录以及文件等。

一、文件目录常用函数

在进行文件和目录操作时,一般会用到以下几种操作。

1、获得当前;路径

在python中可以使用os.getcwd()函数获得当前的路径。

os.getcwd()
    '''帮助文档:Return a unicode string representing the current working directory.'''

该函数不需要传递参数,它返回当前的目录。需要说明的是,当前目录并不是之脚本所在的目录,而是所运行脚本的目录。

修改当前脚本的目录使用os.chdir()函数

os.chdir()
'''帮助文档:chdir(path)
    Change the current working directory to the specified path.
    
    path may always be specified as a string.
    On some platforms, path may also be specified as an open file descriptor.
      If this functionality is unavailable, using it raises an exception.'''

2、获得目录中的内容

在python中可以使用os.listdir()函数获得指定目录中的内容。

os.listdir(path)
''' 帮助文档:listdir(path=None)
    Return a list containing the names of the files in the directory.
    
    path can be specified as either str, bytes, or a path-like object.  If path is bytes,
      the filenames returned will also be bytes; in all other circumstances
      the filenames returned will be str.
    If path is None, uses the path='.'.
    On some platforms, path may also be specified as an open file descriptor;\
      the file descriptor must refer to a directory.
      If this functionality is unavailable, using it raises NotImplementedError.
    
    The list is in arbitrary order.  It does not include the special
    entries '.' and '..' even if they are present in the directory.'''

path参数:要获得内容目录的路径

3、创建目录

在python中可以使用os.mkdir()函数创建目录。

os.mkdir(path)
'''帮助文档mkdir(path, mode=511, *, dir_fd=None)
    Create a directory.
    
    If dir_fd is not None, it should be a file descriptor open to a directory,
      and path should be relative; path will then be relative to that directory.
    dir_fd may not be implemented on your platform.
      If it is unavailable, using it will raise a NotImplementedError.
    
    The mode argument is ignored on Windows.'''

path参数:要创建目录的路径

os.mkdir()函数只能创建一个目录,也就是说路径参数除了最后面要创建的那个目录不存在,路径之前的所有目录必须存在否则就会出现错误,并且当这个目录存在时也会出现错误“当文件已存在,无法创建该文件”

为此我们可以使用另一个函数os.makedirs()函数来创建多级空目录

os.makedirs(path)
'''帮助文档:makedirs(name, mode=511, exist_ok=False)
    makedirs(name [, mode=0o777][, exist_ok=False])
    
    Super-mkdir; create a leaf directory and all intermediate ones.  Works like
    mkdir, except that any intermediate path segment (not just the rightmost)
    will be created if it does not exist. If the target directory already
    exists, raise an OSError if exist_ok is False. Otherwise no exception is
    raised.  This is recursive.'''

path参数:要创建的多级空目录,最后一个目录必须不存在,否则会产生错误”当文件已存在,无法创建该目录“

4、删除目录

在python中可以使用os.rmdir()函数删除目录

os.rmdir(path)
'''帮助文档:rmdir(path, *, dir_fd=None)
    Remove a directory.
    
    If dir_fd is not None, it should be a file descriptor open to a directory,
      and path should be relative; path will then be relative to that directory.
    dir_fd may not be implemented on your platform.
      If it is unavailable, using it will raise a NotImplementedError.'''

path参数:要删除的目录的路径,要删除的目录必须是空目录否则会产生错误”目录不是空的“

为此我们可以使用另一个函数os.removedirs()来删除多级空目录,目录必须为空否则会产生错误”目录不是空的“

5、判断是否是目录

在python中可以使用os.path.isdir()函数判断某一路径是否为目录。

os.path.isdir(path)
'''帮助文档:_isdir(path, /)
    Return true if the pathname refers to an existing directory.'''

path参数:要进行判断的路径

6、判断是否为文件

在python中可以使用os.path.isfile()函数判断某一路径是否为文件。

os.path.isfile(path)
'''帮助文档:isfile(path)
    Test whether a path is a regular file'''

path参数:要进行判断的路径

 7、判断是否是绝对路径

os.path.isabs()函数判断路径是否是绝对路径

os.path.isabs(path)
'''帮助文档:isabs(s)
    Test whether a path is absolute'''

path参数:要判断的的路径

8、检验路径是否真的存在

os.path.exists()函数判断路径是否真的存在

os.path.exists(path)
'''帮助文档:exists(path)
    Test whether a path exists.  Returns False for broken symbolic links'''

path参数:要判断的路径

9、分离路径与文件名

os.path.split(path)
'''帮组文档:split(p)
    Split a pathname.
    
    Return tuple (head, tail) where tail is everything after the final slash.
    Either part may be empty.'''

path参数:要进行分离的路径

10、分离文件扩展名

os.path.splitext(path)
'''帮助文档:splitext(p)
    Split the extension from a pathname.
    
    Extension is everything from the last dot to the end, ignoring
    leading dots.  Returns "(root, ext)"; ext may be empty.'''

path参数:要进行分离的路径

11、获取路径名

os.path.dirname(filename)通过文件的路径只获取路径名

os.path.dirname(filename)
'''帮助文档:dirname(p)
    Returns the directory component of a pathname'''

path参数:文件的具体路径

12、获取文件名

os.path.basename(filename)通过路径获取文件名

os.path.basename(filename)
'''帮助文档:basename(p)
    Returns the final component of a pathname'''

path参数:文件的具体路径

13、读取和设置环境变量

os.getenv()函数获取环境变量os.putenv()设置环境变量

os.getenv()
'''帮助文档:getenv(key, default=None)
    Get an environment variable, return None if it doesn't exist.
    The optional second argument can specify an alternate default.
    key, default and the result are str.'''

os.putenv()
'''帮助文档:putenv(name, value, /)
  Change or add an environment variable.'''

14、给出当前平台使用的行终止符

15、指示你正在使用的平台

os.name()函数指示你当前使用的平台

windows平台为’nt‘

16、获取文件属性

os.stat(file)函数获取文件的属性

os.stat()
'''帮助文档:stat(path, *, dir_fd=None, follow_symlinks=True)
    Perform a stat system call on the given path.
    
      path
        Path to be examined; can be string, bytes, a path-like object or
        open-file-descriptor int.
      dir_fd
        If not None, it should be a file descriptor open to a directory,
        and path should be a relative string; path will then be relative to
        that directory.
      follow_symlinks
        If False, and the last element of the path is a symbolic link,
        stat will examine the symbolic link itself instead of the file
        the link points to.
    
    dir_fd and follow_symlinks may not be implemented
      on your platform.  If they are unavailable, using them will raise a
      NotImplementedError.'''

17、重命名文件或者目录

os.rename(old, new)函数重命名文件或者目录

os.rename(old, new)
'''帮助文档:rename(src, dst, *, src_dir_fd=None, dst_dir_fd=None)
    Rename a file or directory.
    
    If either src_dir_fd or dst_dir_fd is not None, it should be a file
      descriptor open to a directory, and the respective path string (src or dst)
      should be relative; the path will then be relative to that directory.
    src_dir_fd and dst_dir_fd, may not be implemented on your platform.
      If they are unavailable, using them will raise a NotImplementedError.'''

18、获得文件大小

os.path.getsize()
'''帮助文档:getsize(filename)
    Return the size of a file, reported by os.stat().'''

猜你喜欢

转载自www.cnblogs.com/1328497946TS/p/11628432.html