Skip to main content

Python Python的os包

Published 2 min readMarkdown
Python Python的os包

Python的os包

os的文件与目录函数介绍

  • import os
函数名参数介绍举例返回值
getcwd无返回当前的路径os.getcwd()字符串
listdirpath返回制定路径下所有的文件或文件夹os.listdir('c//Windows')返回一个列表
makedirsPath mode创建多级文件夹os.makedir('d//imooc/py')无
removedirspath删除多级文件夹os.removedirs('d://imooc/py')无
renameOldname newname给文件或文件夹改名os.rename('d://imooc', 'd//imoc')无
rmdirpath只能删除空文件夹os.rmdir('d://imooc')无
代码
# coding:utf-8

import os

current_path = os.getcwd()
print(current_path)

new_path = '%s/test1' % current_path
# os.makedirs(new_path)

data = os.listdir(current_path)
print(data)

new_path2 = '%s/test2/abc' % current_path
# os.makedirs(new_path2)
# os.makedirs('test3')

# os.removedirs('test2/abc')
# os.rename('test3', 'test3_new')
# os.rename('test1.py', 'python_test1.py')

# os.rmdir('%s/test3_new' % current_path)
os.rmdir('test1')

os.path模块常用函数介绍

函数名参数介绍举例返回值
existsPath文件或路径是否存在os.path.exists('d://')bool类型
isdirPath是否是路径os.path.isdir('d://')bool类型
isabsPath是否是绝对路径os.path.isabs('test')bool类型
isfilePath是否是文件os.path.isfile('d://a.py')bool类型
joinPath, path*路径字符串合并os.path.join('d://', 'test')字符串
splitPath以最后以层路径为基准切割os.path.split('d://test')列表

代码

# coding:utf-8

import os
import os.path

current_path = os.getcwd()
print(current_path)
print(os.path.isabs(current_path))
print(os.path.isabs('animal'))

new_path = '%s/test1' % current_path
if os.path.exists(new_path):
    os.makedirs(new_path)

data = os.listdir(current_path)
print(data)

new_path2 = os.path.join(current_path, 'test2', 'abc')
print(new_path2)
if os.path.exists(new_path2):
    os.makedirs(new_path2)
if os.path.exists('test3'):
    os.makedirs('test3')

if os.path.exists('test2/abc'):
    os.removedirs('test2/abc')
if os.path.exists('test3'):
    os.rename('test3', 'test3_new')
if os.path.exists('test1.py'):
    os.rename('test1.py', 'python_test1.py')

if os.path.exists('%s/test3_new'):
    os.rmdir('%s/test3_new' % current_path)

if os.path.exists('test1'):
    os.rmdir('test1')
print(dir(os))

current_path = current_path + '/package_os.py'
print(os.path.isfile(current_path))
print(os.path.split(current_path))
print(os.path.isdir(os.path.split(current_path)[0]))

No comments yet. Be the first to comment.

More from this blog