Python-22 文件系统:os模块

本文详细介绍了Python中的OS模块及其子模块os.path的功能和用法,包括文件和目录的基本操作、路径解析等,帮助读者掌握利用Python进行文件系统操作的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

模块

>>> random,randint(1,10)
Traceback (most recent call last):
  File "<pyshell#0>", line 1, in <module>
    random,randint(1,10)
NameError: name 'random' is not defined
>>> import random
>>> secret = random.randint(1,10)
>>> secret
1
>>> 

模块是一个包含你定义的函数和变量的文件,其后缀名是.py。模块可以被别的程序引入,以使用该模块中的函数等功能。


OS模块

OS(Operating System)


os模块中关于文件/目录常用函数使用方法

   函数名        使用方法     
getcwd()
返回当前工作目录
chdir(path)
改变当前目录
listdir(path='.')
列举指定目录中的文件名('.'表示当前目录,'..'表示上一级目录)
mkdir(path)
创建单层目录,如该目录已经存在抛出异常
makedirs(path)
递归创建多层目录,如该目录已经存在抛出异常,注意:'E:\\a\\b'和
'E:\\a\\c'并不会冲突
remove(path)
删除文件
rmdir(path)
删除单层目录,如该目录非空则抛出异常
removedirs(path) 递归删除目录,从子目录到父目录逐层尝试删除,遇到目录非空则抛出异常
rename(old,new)
将文件old重命名为new
system(command)      
运行系统的shell命令
walk(top)
遍历top路径以下所有的子目录,返回一个三元组:(路径,[包含目录],[包含文件])

以下是支持路径操作中常用到的一些定义,支持所有平台
os.curdir
指代当前目录('.')
os.pardir
指代上一级目录('..')
os.sep
输出操作系统特定的路径分隔符(Win下为'\\',Linux下为'/')
os.linesep
当前平台使用的行终止符(Win下为'\r\n',Linux下为'\n')
os.name
指代当前使用的操作系统(包括:'posix','nt','mac','os2','ce','java')

>>> import os
>>> os.getcwd()
'D:\\Python'
>>> os.chdir('E:\\')
>>> os.getcwd()
'E:\\'
>>> 

>>> os.listdir('.')
['$RECYCLE.BIN', 'Activiti', 'activiti-5.10', 'downloads','Image', 'JAVA', 'Mine', 'Music', 'record.txt', 'System Volume Information', 'test.txt', 'Video', '课程']
>>> 

>>> os.mkdir('E:\\A')
>>> os.mkdir('E:\\A\\B')
>>> os.mkdir('E:\\C\\B')
Traceback (most recent call last):
  File "<pyshell#13>", line 1, in <module>
    os.mkdir('E:\\C\\B')
FileNotFoundError: [WinError 3] 系统找不到指定的路径。: 'E:\\C\\B'
>>> 

>>> os.makedirs('E:\\C\\B')
>>> 

>>> os.remove('E:\\text.txt')
Traceback (most recent call last):
  File "<pyshell#15>", line 1, in <module>
    os.remove('E:\\text.txt')
FileNotFoundError: [WinError 2] 系统找不到指定的文件。: 'E:\\text.txt'
>>> os.remove('E:\\text.txt')
>>> 

>>> os.rmdir('E:\\A')
Traceback (most recent call last):
  File "<pyshell#17>", line 1, in <module>
    os.rmdir('E:\\A')
OSError: [WinError 145] 目录不是空的。: 'E:\\A'
>>> os.rmdir('E:\\A\\B')
>>> 
>>> os.removedirs('E:\\C')
Traceback (most recent call last):
  File "<pyshell#26>", line 1, in <module>
    os.removedirs('E:\\C')
  File "D:\Python\lib\os.py", line 253, in removedirs
    rmdir(name)
OSError: [WinError 145] 目录不是空的。: 'E:\\C'
>>> os.removedirs('E:\\C\\B')

>>> os.rename('E:\\Teet.txt','E:\\Tcct.txt')
>>> os.listdir('.')
['$RECYCLE.BIN', 'A', 'Activiti', 'activiti-5.10','downloads', 'Image', 'JAVA', 'Mine', 'Music', 'record.txt', 'System Volume Information', 'Tcct.txt', 'test.txt', 'Video']
>>> 

>>> os.system('cmd')
-1073741510
>>> os.system('calc') #计算器
0
>>> 

>>> import os
>>> os.curdir
'.'
>>> os.pardir
'..'
>>> os.getcwd()
'D:\\Python'
>>> os.sep
'\\'
>>> os.linesep
'\r\n'
>>> os.name
'nt'
>>> 


os.path模块中关于路径常用的函数使用方法

    函数名         使用方法    
basename(path)      
去掉目录路径,单独返回文件名                          
dirname(path)
去掉文件名,单独返回目录路径
join(path1[,path2[,...]])    
将path1,path2各部分组合成一个路径名
split(path)
分割文件名与路径,返回(f_path,f_name)元组。如果完全使用目录,它也会将最后
一个目录作为文件名分离,且不会判断文件或者目录是否存在                                                       
splitext(path)
分离文件名与扩展名,返回(f_name,f_extension)元组
getsize(file)
返回指定文件尺寸,单位是字节
getatime(file)
返回指定文件最近的访问时间(浮点型秒数,可用time模块的gmtime()或
者localtime()函数换算)
getctime(file)
返回指定文件的创建时间(浮点型秒数,可用time模块的gmtime()或localtime()函数换算)
getmtime(file)
返回指定文件最新的修改时间(浮点型秒数,可用time模块的gmtime()或localtime()函数换算)

以下函数返回True或False
exits(path)
判断指定路径(目录或文件)是否存在
isabs(path)
判断指定路径是否为绝对路径
isdir(path)
判断指定路径是否存在且是一个目录
isfile(path)
判断指定路径是否存在且是一个文件
islink(path)
判断指定路径是否存在且是一个符号链接
ismount(path)
判断指定路径是否存在且是一个挂载点
samefile(path1,path2)
判断path1和path2两个路径是否指向同一个文件

>>> os.chdir('E:\\')
>>> os.getcwd()
'E:\\'

>>> os.path.basename('E:\\')
''
>>> os.path.basename('E:\\Tcct.txt')
'Tcct.txt'
>>>


>>> os.path.dirname('E:\\Tcct.txt')
'E:\\'
>>> 

>>> os.path.split('E:\\Tcct.txt')
('E:\\', 'Tcct.txt')
>>> 

>>> os.path.splitext('E:\\Tcct.txt')
('E:\\Tcct', '.txt')
>>> 


>>> os.path.getsize('E:\\Tcct.txt')
8
>>> os.path.getsize('E:\\test.txt')
8
>>> 

>>> os.path.getatime('E:\\test.txt')
1501677239.939833
>>> import time
>>> time.gmtime(os.path.getatime('E:\\test.txt'))
time.struct_time(tm_year=2017, tm_mon=8, tm_mday=2, tm_hour=12, tm_min=33, tm_sec=59, tm_wday=2, tm_yday=214, tm_isdst=0)
>>> time.localtime(os.path.getatime('E:\\test.txt'))
time.struct_time(tm_year=2017, tm_mon=8, tm_mday=2, tm_hour=20, tm_min=33, tm_sec=59, tm_wday=2, tm_yday=214, tm_isdst=0)
>>> 


>>> time.gmtime(os.path.getctime('E:\\test.txt'))
time.struct_time(tm_year=2017, tm_mon=8, tm_mday=2, tm_hour=12, tm_min=33, tm_sec=59, tm_wday=2, tm_yday=214, tm_isdst=0)
>>> time.localtime(os.path.getctime('E:\\test.txt'))
time.struct_time(tm_year=2017, tm_mon=8, tm_mday=2, tm_hour=20, tm_min=33, tm_sec=59, tm_wday=2, tm_yday=214, tm_isdst=0)
>>> 

>>> time.gmtime(os.path.getmtime('E:\\test.txt'))
time.struct_time(tm_year=2017, tm_mon=8, tm_mday=2, tm_hour=12, tm_min=36, tm_sec=59, tm_wday=2, tm_yday=214, tm_isdst=0)
>>> time.localtime(os.path.getmtime('E:\\test.txt'))
time.struct_time(tm_year=2017, tm_mon=8, tm_mday=2, tm_hour=20, tm_min=36, tm_sec=59, tm_wday=2, tm_yday=214, tm_isdst=0)
>>> 

返回True或False

>>> os.path.exists('E:\\TT.txt')
False
>>> os.path.exists('E:\\Tcct.txt')
True
>>> 


>>> os.path.isabs('E:\\Tcct.txt')
True
>>> os.path.isabs('.\\Tcct.txt')
False
>>> 

>>> os.makedirs('E:\\A\\B\\C\\D')
>>> os.path.isdir('E:\\A\\B\\C\\D')
True
>>> os.path.isdir('E:\\A\\B\\C\\E')
False
>>> 


>>> f = open('E:\\A\\B\\C\\D\\uaa.txt','w')
>>> f.write('United States of America')
24
>>> f.close()
>>> os.path.isfile('E:\\A\\B\\C\\D\\uaa.txt')
True
>>> 


>>> os.path.ismount('E:\\A\\B\\C')
False
>>> os.path.ismount('E:\\')
True
>>> os.path.ismount('E:')
True
>>> 


>>> os.path.samefile('E:\\A\\B\\C\\D\\uaa.txt','.\\A\\B\\C\\D\\uaa.txt')
True
>>> 


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值