Python理论10:系统操作相关


上一章介绍了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模块有时间在更

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值