Python文件操作实用函数

文件操作

file_path=/Users/demon.li/log.txt
分割函数
print os.path.split(file_path)

Output:
('/Users/demon.li', 'log.txt')
#返回文件名
print os.path.basename(file_path)

Output:
log.txt
#返回文件路径 
print os.path.dirname(file_path)

Output:
/Users/demon.li
#分离文件名与扩展名 
print os.path.splitext(file_path)

Output:
('/Users/demon.li/log', '.txt')
查询函数
#判断文件/目录是否存在
print os.path.exists(file_path)

Output:
存在:True
不存在:False
#判断是否为绝对路径
print os.path.isabs(file_path)

Output:
True/False
#判断是否为文件且存在
print os.path.isfile(file_path)

Output:
True/False
#判断是否为目录且存在
print os.path.isdir(file_path)

Output:
True/False
#指定路径是否存在且为一个符号链接 
print os.path.islink(file_path)

Output:
True/False
#输出当前工作目录路径
print os.getcwd()

目录操作

dir_path=/Users/demon.li
#输出目录下的所有文件和目录列表
print os.listdir(dir_path)
#创建目录
print os.mkdir(dir_path)
#循环创建目录
print os.makedirs(dir_path)

Other

#与平台相关的路径分隔符
print os.sep
#执行操作系统相关的命令
#注意区分Windows和类Unix命令是不同的
command="cp ~/log.txt ~/log_new.txt"
os.system(command)
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值