python中OS模块的常用命令

python中OS模块的常用命令

Meringue
5/6/2017

import os
os_path = '/home/meringue/Documents/PythonFile/osNotes/'
## 更改当前工作目录
os.chdir(os_path)
## 获取当前工作目录
os.getcwd()
'/home/meringue/Documents/PythonFile/osNotes'
## 返回当前系统(windows: nt; Linux: posix) 
os.name
'posix'
## 创建文件和文件目录
for i in range(5):
    os.mknod('test_file'+str(i)+'.txt') # 文件
    os.mkdir('test_docu'+str(i)) # 文件目录
os.makedirs('./test_docu5/test_docu0/') # 多层文件夹路径
## 获取指定路径下的文件列表(不区分文件和文件夹)
os.listdir(os_path)
['.ipynb_checkpoints',
 'test_docu2',
 'test_docu1',
 'test_docu3',
 'test_file2.txt',
 'test_docu4',
 'test_docu5',
 'osNotes.ipynb',
 'test_file3.txt',
 'test_docu0',
 'test_file0.txt',
 'test_file4.txt',
 'test_file1.txt']
## 删除当前目录下指定文件或文件夹
os.remove('./test_file0.txt') # 文件
os.rmdir('./test_docu0/') # 文件夹
## 判断指定对象是否为文件或目录(返回True或False)
print os.path.isfile('./test_file1.txt')
print os.path.isdir('./test_docu5/test_docu0/')
True
True
## 判断指定对象是否存在(两个对象均已在上述步骤中被删除)
print os.path.exists('./test_file0.txt')
print os.path.exists('./test_docu0/')
False
False
## 返回路径的目录和文件名
print os.path.split(os_path)
print os.path.split(os_path+'test_file1.txt')
('/home/meringue/Documents/PythonFile/osNotes', '')
('/home/meringue/Documents/PythonFile/osNotes', 'test_file1.txt')
## 返回绝对路径
print os.path.abspath('./test_file1.txt')
print os.path.abspath('./test_docu1/')
/home/meringue/Documents/PythonFile/osNotes/test_file1.txt
/home/meringue/Documents/PythonFile/osNotes/test_docu1
## 连接目录和文件名
os.path.join(os_path,'test_file1.txt')
'/home/meringue/Documents/PythonFile/osNotes/test_file1.txt'
## 返回文件名和文件路径
print os.path.basename(os_path+'test_file1.txt')
print os.path.dirname(os_path+'test_file1.txt')
test_file1.txt
/home/meringue/Documents/PythonFile/osNotes
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值