Python编程:os模块

os属性


import os

print(os.curdir) # 当前目录 .
print(os.pardir) # 父目录 ..
print(os.name)  # 平台名称 win nt linux posix
print(os.sep)  # separator路径分隔符win \\ linux /
print(os.linesep) # 行终止符 win \r\n  linux \n
print(os.pathsep)  # 分隔文件路径 ;
print(os.extsep)  # extension扩展名 .

os方法


import os

print(os.getcwd())  # 返回当前工作目录
print(os.chdir( r"dir" ))  # 改变工作目录,相当于shell下cd
os.makedirs("dir1/dir2")  # 生成多层递归目录,存在则无法创建
os.removedirs("dir1/dir2")  # 递归删除空目录
os.mkdir("dirname")  # 生成单级目录,存在则无法创建
os.rmdir("dirname")  # 删除单级空目录,不为空则无法删除
print(os.listdir())  # list返回指定目录下所有文件和子目录,包括隐藏文件
os.remove("file.txt") # 删除一个文件
os.rename("oldname", "newname")  # 重命名文件/目录

os.system("ipconfig /all")  # 运行shell命令,直接显示
print(os.environ) # 返回系统环境变量

path模块


import os

print(os.path.abspath("file.txt"))  #返回绝对路径
print(os.path.split("dirname/file.txt"))  #tuple分隔目录和文件名
print(os.path.splitext("file.txt"))  #tuple分隔文件名和扩展名  (file, .txt)
print(os.path.dirname("dirname/file.txt"))  #返回目录
print(os.path.basename("dirname/file.txt")) # 返回文件名
print(os.path.join("dir","file.txt")) # 返回一个组合路径

print(os.path.exists("file.txt")) # bool判断文件是否存在
print(os.path.isabs("file.txt")) # bool判断是否为绝对路径
print(os.path.isfile("file.txt")) # bool判断是否为一个文件
print(os.path.isdir("dir")) # bool判断是否为一个目录

print(os.stat("file.txt"))  # tuple获取文件/目录信息
print(os.path.getatime("file.txt")) # 时间戳,返回最后存取时间
print(os.path.getmtime("file.txt")) # 时间戳,返回最后修改时间

# 时间戳转为格式化时间字符串
# time.strftime("%Y-%m-%d %H:%M:%S",time.localtime("timestamp")

遍历所有文件和文件夹


import os

# 游走目录树
for root, dirs, files in os.walk("."):
    for file in files:
        print(os.path.join(root, file))
    for dir in dirs:
        print(os.path.join(root, dir))

help(os)

  • all functions from posix, nt or ce, e.g. unlink, stat, etc.
  • os.path is either posixpath or ntpath
  • os.name is either ‘posix’, ‘nt’ or ‘ce’.
  • os.curdir is a string representing the current directory (‘.’ or ‘:’)
  • os.pardir is a string representing the parent directory (‘..’ or ‘::’)
  • os.sep is the (or a most common) pathname separator (‘/’ or ‘:’ or ‘\’)
  • os.extsep is the extension separator (always ‘.’)
  • os.altsep is the alternate pathname separator (None or ‘/’)
  • os.pathsep is the component separator used in $PATH etc
  • os.linesep is the line separator in text files (‘\r’ or ‘\n’ or ‘\r\n’)
  • os.defpath is the default search path for executables
  • os.devnull is the file path of the null device (‘/dev/null’, etc.)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值