os / os.path modules
OS模块简单的来说它是一个Python的系统编程的操作模块,可以处理文件和目录这些我们日常手动需要做的操作。
官方对此的注释为: Miscellaneous(多样的) operating system interfaces
1. os module
os.name 获取操作系统标识(在window中是'nt') 如果想要详细的操作系统内容,可以如下
import platform
b1 = platform.uname()
print(b1)
2.1 abspath
OS模块简单的来说它是一个Python的系统编程的操作模块,可以处理文件和目录这些我们日常手动需要做的操作。
官方对此的注释为: Miscellaneous(多样的) operating system interfaces
1. os module
os.name 获取操作系统标识(在window中是'nt') 如果想要详细的操作系统内容,可以如下
import platform
b1 = platform.uname()
print(b1)
结果: uname_result(system='Windows', node='BJXX-LYH', release='7', version='6.1.7601', machine='AMD64', processor='Intel64 Family 6 Model 60 Stepping 3, GenuineIntel')
常用functions
1.1 chdir
# 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.
os.chdir('D:\eclipse\workspace\python_201510\src')
# 注:linux环境中的左斜线和windows中的右斜线
1.2 getcwd
# getcwd(...)
# getcwd() -> path
#
# Return a unicode string representing the current working directory.
print(os.getcwd())
# D:\eclipse\workspace\python_201510\src
1.3 listdir
# listdir(...)
# listdir(path='.') -> list_of_filenames
#
# Return a list containing the names of the files in the directory.
# The list is in arbitrary order. It does not include the special
# entries '.' and '..' even if they are present in the directory.
#
# path can be specified as either str or bytes. If path is bytes,
# the filenames returned will also be bytes; in all other circumstances
# the filenames returned will be str.
# 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.
import os
os.chdir('D:\eclipse\workspace\python_201510\src')
print(os.listdir())
1.4 makedirs
# 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.
os.makedirs("D:\HeadFirstPython\chapter1b\lyh")
# 当os.mkdir("D:\HeadFirstPython\chapter1b\lyh")时会报错chapter1b不存在,即makedir创建目录时,其父目录必须存在
1.5 mkdir
# mkdir(...)
# mkdir(path, mode=0o777, *, 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.
os.mkdir("D:\HeadFirstPython\chapter1b")
1.6 remove
# remove(...)
# remove(path, *, dir_fd=None)
#
# Remove a file (same as unlink()).
#
# 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.
os.remove("D:\HeadFirstPython\chapter1\\150806.py")
1.7 removedirs
# removedirs(name)
# removedirs(name)
#
# Super-rmdir; remove a leaf directory and all empty intermediate
# ones. Works like rmdir except that, if the leaf directory is
# successfully removed, directories corresponding to rightmost path
# segments will be pruned away until either the whole path is
# consumed or an error occurs. Errors during this latter phase are
# ignored -- they generally mean that a directory was not empty.
os.removedirs("D:\HeadFirstPython\chapter1b\lyh") 如果lyh是个空的目录,则删除lyh目录;如果删除lyh目录后chapter1b是空目录,则删除chapter1b,依次类推
1.8 rename
# rename(...)
# 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.
os.rename("D:\HeadFirstPython\chapter1\\150812.py", "D:\HeadFirstPython\chapter1\\150812b.py")
1.9 rmdir
# rmdir(...)
# 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.
# 删除空目录(删除非空目录, 使用shutil.rmtree())
os.removedirs("D:\HeadFirstPython\chapter1b")
shutil.rmtree("D:\HeadFirstPython\chapter1b")
1.10 system
# system(...)
# system(command) -> exit_status
#
# Execute the command (a string) in a subshell.
os.system('cmd')
1.11 unlink
# unlink(...)
# unlink(path, *, dir_fd=None)
#
# Remove a file (same as remove()).
#
# 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.
os.unlink("D:\HeadFirstPython\chapter1\\150806.py")
1.12 utime
# utime(...)
# utime(path, times=None, *, ns=None, dir_fd=None, follow_symlinks=True)
# Set the access and modified time of 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.
#
# If times is not None, it must be a tuple (atime, mtime);
# atime and mtime should be expressed as float seconds since the epoch.
# If ns is not None, it must be a tuple (atime_ns, mtime_ns);
# atime_ns and mtime_ns should be expressed as integer nanoseconds
# since the epoch.
# If both times and ns are None, utime uses the current time.
# Specifying tuples for both times and ns is an error.
#
# 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.
# If follow_symlinks is False, and the last element of the path is a symbolic
# link, utime will modify the symbolic link itself instead of the file the
# link points to.
# It is an error to use dir_fd or follow_symlinks when specifying path
# as an open file descriptor.
# dir_fd and follow_symlinks may not be available on your platform.
# If they are unavailable, using them will raise a NotImplementedError.
# 修改文件时间戳
print(os.utime("D:\HeadFirstPython\chapter1b\lyh"))
# 返回指定的path文件的访问和修改的时间。如果时间是 None, 则文件的访问和修改设为当前时间 。 否则, 时间是一个 2-tuple数字, (atime, mtime) 用来分别作为访问和修改的时间.
2. os.path module2.1 abspath
# abspath(path)
# Return the absolute version of a path.
# 获得绝对路径 就是可以根据一个文件,求到这个文件所在的路径
print(os.path.abspath('151019.py'))
# D:\eclipse\workspace\python_201510\src\151019.py
2.2 basename
# basename(p)
# Returns the final component of a pathname
abs_path = 'D:\eclipse\workspace\python_201510\src\\151019.py'
print(os.path.basename(abs_path.replace('\\', '\\\\')))
# 151019.py
# 结论:basename和dirname是split的组成部分
2.3 dirname
# dirname(p)
# Returns the directory component of a pathname
abs_path = 'D:\eclipse\workspace\python_201510\src\\151019.py'
print(os.path.dirname(abs_path.replace('\\', '\\\\')))
# D:\\eclipse\\workspace\\python_201510\\src
2.4 exists
# exists(path)
# Test whether a path exists. Returns False for broken symbolic links
print(os.path.exists('151019.py'))
# True
2.5 isabs
# isabs(s)
# Test whether a path is absolute
print(os.path.isabs('D:\eclipse\workspace\python_201510\src\151019.py'))
# True
2.6 isdir
# isdir = _isdir(...)
# Return true if the pathname refers to an existing directory.
rel_path = 'D:\eclipse\workspace\python_201510\src'
print(os.path.isdir(rel_path))
# True
2.7 join
# join(path, *paths)
# Join two (or more) paths.
dir_name = 'D:\\eclipse\\workspace\\python_201510\\src\\'
base_name = '151019.py'
print(os.path.join(dir_name, base_name))
# D:\eclipse\workspace\python_201510\src\151019.py
2.8 normcase
# normcase(s)
# Normalize case of pathname.
# Makes all characters lowercase and all slashes into backslashes.
abs_path = 'D:\eclipse\workspace\python_201510\src\\151019.py'
print(os.path.normcase(abs_path))
# d:\eclipse\workspace\python_201510\src\151019.py
2.9 normpath
# normpath(path)
# Normalize path, eliminating double slashes, etc.
abs_path = 'D:\eclipse\workspace\python_201510\src\\151019.py'
print(os.path.normpath(abs_path))
# D:\eclipse\workspace\python_201510\src\151019.py
2.10 realpath
# realpath = abspath(path)
# Return the absolute version of a path.
print(os.path.realpath('151019.py'))
# D:\eclipse\workspace\python_201510\src\151019.py
2.11 relpath
# relpath(path, start='.')
# Return a relative version of a path
abs_path = 'D:\eclipse\workspace\python_201510\src\\151019.py'
print(os.path.relpath(abs_path, start= '.'))
# 151019.py
# 从start开始计算相对路径
# 结论: realpath 和 relpath具有相反的功能
2.12 split
# split(p)
# Split a pathname.
# Return tuple (head, tail) where tail is everything after the final slash.
# Either part may be empty.
abs_path = 'D:\\eclipse\\workspace\\python_201510\\src\\151019.py'
print(os.path.split(abs_path)[0])
print(os.path.split(abs_path)[1])
# D:\eclipse\workspace\python_201510\src
# 151019.py
2.13 splitdirve
# splitdrive(p)
# Split a pathname into drive/UNC sharepoint and relative path specifiers.
# Returns a 2-tuple (drive_or_unc, path); either part may be empty.
#
# If you assign
# result = splitdrive(p)
# It is always true that:
# result[0] + result[1] == p
#
# If the path contained a drive letter, drive_or_unc will contain everything
# up to and including the colon. e.g. splitdrive("c:/dir") returns ("c:", "/dir")
#
# If the path contained a UNC path, the drive_or_unc will contain the host name
# and share up to but not including the fourth directory separator character.
# e.g. splitdrive("//host/computer/dir") returns ("//host/computer", "/dir")
#
# Paths cannot contain both a drive letter and a UNC path.
abs_path = 'D:\eclipse\workspace\python_201510\src\\151019.py'
print(os.path.splitdrive(abs_path))
# ('D:', '\\eclipse\\workspace\\python_201510\\src\\151019.py')
2.14 splitext
# 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.
abs_path = 'D:\\eclipse\\workspace\\python_201510\\src\\151019.py'
print(os.path.splitext(abs_path)[0])
print(os.path.splitext(abs_path)[1])
# D:\eclipse\workspace\python_201510\src\151019
# .py
2.15 splitunc
# splitunc(p)
# Deprecated since Python 3.1. Please use splitdrive() instead;
# it now handles UNC paths.#
# Split a pathname into UNC mount point and relative path specifiers.#
# Return a 2-tuple (unc, rest); either part may be empty.
# If unc is not empty, it has the form '//host/mount' (or similar
# using backslashes). unc+rest is always the input path.
# Paths containing drive letters never have an UNC part.
abs_path = 'D:\eclipse\workspace\python_201510\src\\151019.py'
print(os.path.splitunc(abs_path))
# ('', 'D:\\eclipse\\workspace\\python_201510\\src\\151019.py')