上一章介绍了python中文件读写的方法和技巧,这一章主要来谈一谈python与系统操作有关的三个模块,及其用法。
OS模块
os模块负责程序与操作系统的交互,提供了访问操作系统底层的接口;由于python是跨平台的,所以可以在多个平台上使用os模块。
OS模块关于文件/目录的函数
getcwd( )
该函数返回当前工作目录,用于查看当前工作目录
import os
print(os.getcwd())
执行结果:
C:\Users\MyPC\.PyCharmCE2018.3\config\scratches\python训练
chdir(path)
改变工作目录
import os
os.chdir('C:\\Users\\MyPC\\.PyCharmCE2018.3\\config\\scratches\\python test')
print(os.getcwd())
执行结果:
C:\Users\MyPC\.PyCharmCE2018.3\config\scratches\python test
listdir(path)
列举当前目录中的文件名
import os
print(os.listdir('C:\\Users\MyPC\.PyCharmCE2018.3\config\scratches\python test'))
执行结果:
['test.py', 'test1.py']
mkdir(path)
创建单层目录,如该目录已存在则抛出异常
import os
os.mkdir('D:\\test')
执行结果,在D盘创建了名为test的文件夹
如果已存在抛出异常
FileExistsError: [WinError 183] 当文件已存在时,无法创建该文件
makedirs(path)
递归创建多层目录,如该目录已存在抛出异常
import os
os.makedirs('D:\\test\\a\\b')
执行结果,在test目录下创建了a目录下的b
remove(path)
删除文件
import os
os.remove('D:\\test\\a\\1.txt')
若无该文件则异常
FileNotFoundError: [WinError 2] 系统找不到指定的文件。
rmdir(path)
删除单层目录
import os
os.rmdir('d:\\test\\a\\b')
若不存在该目录,异常
FileNotFoundError: [WinError 2] 系统找不到指定的文件。
如果该目录非空则抛出异常
OSError: [WinError 145] 目录不是空的。
removedirs(path)
递归删除目录,从子目录到父目录逐层尝试删除
import os
os.removedirs('d:\\test\\a\\b')
遇到目录非空则抛出异常
OSError: [WinError 145] 目录不是空的。
rename(old,new)
将文件old重命名为new
import os
os.rename('d:\\test\\1.txt','d:\\test\\2.txt')
system(command)
调用系统命令
import os
os.system('cmd')
walk(top)
遍历top路径以下所有的子目录,返回一个三元组:(路径,[包含目录],[包含文件])
语法:
os.walk(top[, topdown=True[, onerror=None[, followlinks=False]]])
参数:
1.top – 根目录下的每一个文件夹(包含它自己), 产生3-元组 (dirpath, dirnames, filenames)【文件夹路径, 文件夹名字, 文件名】。
2.topdown --可选,为True或者没有指定, 一个目录的的3-元组将比它的任何子文件夹的3-元组先产生 (目录自上而下)。如果topdown为 False, 一个目录的3-元组将比它的任何子文件夹的3-元组后产生 (目录自下而上)。
3.onerror – 可选,是一个函数; 它调用时有一个参数, 一个OSError实例。报告这错误后,继续walk,或者抛出exception终止walk。
示例1:
import os
os.chdir('d:\\test')
for i in os.walk(os.getcwd()):
print(i)
结果:
('d:\\test', ['a'], ['2.txt'])
('d:\\test\\a', ['b'], ['1.txt'])
('d:\\test\\a\\b', ['c'], ['3.txt'])
('d:\\test\\a\\b\\c', [], ['4.txt'])
示例2:
import os
for root,dirs,files in os.walk('d:\\test'):
for name in files:
print(os.path.join(root,name))
for name in dirs:
print(os.path.join(root,name))
结果:
d:\test\2.txt
d:\test\a
d:\test\a\1.txt
d:\test\a\b
d:\test\a\b\3.txt
d:\test\a\b\c
d:\test\a\b\c\4.txt
示例3:
import os
for root,dirs,files in os.walk('d:\\test',topdown = False):
for name in files:
print(os.path.join(root,name))
for name in dirs:
print(os.path.join(root,name))
结果:
d:\test\a\b\c\4.txt
d:\test\a\b\3.txt
d:\test\a\b\c
d:\test\a\1.txt
d:\test\a\b
d:\test\2.txt
d:\test\a
os.path模块中关于路径的常用函数
basename(path)
去掉目录路径,单独返回文件名
os.path.basename('D:\\Reboot\\01\\hello world.py')
结果:
’hello world.py’
dirname(path)
去掉文件名,单独返回目录路径
os.path.dirname('D:\\Reboot\\01\\hello world.py')
结果
’D:\Reboot\01’
join(path1[,path2[,…]])
将path1,path2各部分组成合成一个路径名
os.path.join('d:\\01','Reboot')
结果:
’d:\01\Reboot’
split(path)
分割文件名与路径,返回(f_path,f_name)元组。
如果完全使用目录,它也会将最后一个目录作为文件名分离,且不会判断文件或者目录是否存在。
os.path.split('d:/Reboot/01/hello world.py')
结果:
(‘d:/Reboot/01’, ‘hello world.py’)
splitext(path))
分离文件名与扩展名,返回(f_name,f_extension)元组
os.path.splitext('d:/Reboot/01/hello world.py')
结果:
(‘d:/Reboot/01/hello world’, ‘.py’)
getsize(file))
返回指定文件的尺寸,单位是字节
getatime(file))
返回指定文件最近的访问时间
(浮点型秒数,可用time模块的gmtime()或localtime()函数换算)
import time
time.localtime(os.path.getatime('d:/Reboot/01/hello world.py'))
结果
time.struct_time(tm_year=2018, tm_mon=3, tm_mday=18, tm_hour=11, tm_min=12, tm_sec=1, tm_wday=6, tm_yday=77, tm_isdst=0)
getctime(file))
返回指定文件创建时间
(浮点型秒数,可用time模块的gmtime()或localtime()函数换算)
getmtime(file)
返回指定文件最近的修改时间
(浮点型秒数,可用time模块的gmtime()或localtime()函数换算)
sys模块
shutil模块有时间在更
本文介绍了Python的OS模块,该模块负责程序与操作系统交互,提供底层接口且可跨平台使用。详细讲解了OS模块关于文件/目录的函数,如getcwd、chdir等,以及os.path模块中关于路径的常用函数,像basename、dirname等,并给出部分函数执行结果和示例。

16万+

被折叠的 条评论
为什么被折叠?



