当前位置: 移动技术网 > IT编程>脚本编程>Python > 课时30:文件系统:介绍一个高大上的东西

课时30:文件系统:介绍一个高大上的东西

2018年08月21日  | 移动技术网IT编程  | 我要评论

黄冈市房地产信息网,古今笑话,nba圣诞大战2016

目录:

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

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

  三、课时30课后习题及答案

 

接下来会介绍跟python的文件相关的一些很有用的模块。模块是什么?其实我们写的每一个源代码文件(*.py)都是一个模块。python自身带有非常多使用的模块。

比如刚开始介绍的文字小游戏,里边就用random模块的randint()函数来生成随机数。然而要使用这个randint()函数,直接就调用可不行:

>>> random.randint(0,9)
                              
traceback (most recent call last):
  file "<pyshell#36>", line 1, in <module>
    random.randint(0,9)
nameerror: name 'random' is not defined

正确的做法是先使用import语句导入模块,然后再使用:

>>> import random
                              
>>> random.randint(0,9)
                              
3
>>> random.randint(0,9)
                              
0
>>> random.randint(0,9)
                              
7

 

*******************************************************

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

*******************************************************

首先要介绍的是高大上的os模块,os即operating system的缩写,意思是操作系统。之所以说os模块高大上,是因为对于文件系统的访问,python一般是通过os模块来实现的。

python是跨平台的语言,也就是说,同样的源代码在不同的操作系统不需要修改就可以同样实现。有了os模块,不需要关心什么操作系统下使用什么模块,os模块会帮你选择正确的模块并调用。

下表列举了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路径以下所有的子目录,返回一个三元组:(路径, [包含目录], [包含文件])【具体实现方案请看:第30讲课后作业^_^】
以下是支持路径操作中常用到的一些定义,支持所有平台 os.curdir          指代当前目录('.') os.pardir         指代上一级目录('..') os.sep           输出操作系统特定的路径分隔符(win下为'\\',linux下为'/') os.linesep         当前平台使用的行终止符(win下为'\r\n',linux下为'\n') os.name          指代当前使用的操作系统(包括:'posix',  'nt', 'mac', 'os2', 'ce', 'java')

 

1、getcwd()

在有些情况下,我们需要获得应用程序当前的工作目录(比如要保存临时文件),那么可以使用getcwd()函数获得:

>>> import os
                              
>>> os.getcwd()
                              
'c:\\users\\14158\\appdata\\local\\programs\\python\\python37'

 

2、chdir(path)

用chdir()函数可以改变当前工作目录,比如可以切换到d盘:

>>> os.chdir("d:\\")
                              
>>> os.getcwd()
                              
'd:\\'

 

3、listdir(path='.')

有时候你可能需要知道当前目录下有哪些文件和子目录,那么listdir()函数可以帮你列举出来。path参数用于指定列举的目录,默认值是'.',代表根目录,也可以使用'..'代表上一层目录:

 

>>> os.chdir("c:\\")
                              
>>> os.listdir()
                              
['$recycle.bin', 'aow_drv.log', 'appdata', 'documents and settings', 'hiberfil.sys', 'intel', 'onedrivetemp', 'pagefile.sys', 'pbb.txt', 'perflogs', 'program files', 'program files (x86)', 'programdata', 'recovery', 'swapfile.sys', 'system volume information', 'users', 'windows']
>>> os.listdir("d:\\")
                              
['$recycle.bin', 'bigdata', 'hlddz', 'installconfig.ini', 'java', 'qq图片20180728154834.jpg', 'qq图片20180728155014.jpg', 'qycache', 'rhel-server-7.4-x86_64-dvd.iso', 'system volume information', 'ubuntu-18.04-live-server-amd64.iso', '大二上', '安装包', '小甲鱼', '应用程序', '桌面壁纸']

 

4、mkdir(path)

mkdir()函数用于创建文件夹,如果该文件夹存在,则抛出fileexistserror异常:

>>> os.mkdir("test")
                              
>>> os.listdir()
                              
['$recycle.bin', 'aow_drv.log', 'appdata', 'documents and settings', 'hiberfil.sys', 'intel', 'onedrivetemp', 'pagefile.sys', 'pbb.txt', 'perflogs', 'program files', 'program files (x86)', 'programdata', 'recovery', 'swapfile.sys', 'system volume information', 'test', 'users', 'windows']
>>> os.mkdir("test")
                              
traceback (most recent call last):
  file "<pyshell#57>", line 1, in <module>
    os.mkdir("test")
fileexistserror: [winerror 183] 当文件已存在时,无法创建该文件。: 'test'

 

5、makedirs(path)

makedirs()函数可以用于创建多层目录:

>>> os.makedirs(r".\a\b\c")

效果如图所示:

 

6、remove(path)、rmdir(path) 和removedirs(path)  

remove()函数用于删除指定的文件,注意是删除文件,不是删除目录。如果要删除目录,则用rmdir()函数;如果要删除多层目录,则用removedirs()函数。

>>> os.listdir()                              
['$recycle.bin', 'a', 'aow_drv.log', 'appdata', 'b', 'documents and settings', 'hiberfil.sys', 'intel', 'onedrivetemp', 'pagefile.sys', 'pbb.txt', 'perflogs', 'program files', 'program files (x86)', 'programdata', 'recovery', 'swapfile.sys', 'system volume information', 'test', 'users', 'windows']
>>> os.remove("test")                             
>>> os.rmdir("b")
>>> os.removedirs(r".\a\b\c")

注:在c盘有可能会报错,没有权限。

 

7、rename(old,new)

rename()函数用于重命名文件或文件夹:

>>> os.listdir()
['a','a.txt']                              
>>> os.rename("a","b")
>>> os.rename("a.txt","b.txt")                           
>>> os.listdir()
['b','b.txt']  

 

8、systemf(command)

几乎每个操作系统都会提供一些小工具,system()函数就是用于使用这些小工具:

>>> os.system("calc")#calc是windows自带的计算器

回车后即弹出计算器。

 

9、walk(top)

最后是walk()函数,这个函数在有些时候确实非常有用,可以省去你很多麻烦。该函数的作用是遍历top参数指定路径下的所有子目录,并将结果返回一个三元组(路径,[包含目录],[包含文件])。

>>> for i in os.walk("test"):
         print(i)    

 

另外path模块还提供了一些很实用的定义,分别是:os.curdir表示当前目录;os.pardir表示上一级目录('..');os.sep表示路径的分隔符,比如windows系统下为‘\\’,linux下为‘\’;os.linesep表示当前平台使用的行终止符(在windows下为‘\r\n’,linux下为‘\n’);os.name表示当前使用的操作系统。

 

*******************************************************

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

*******************************************************

 另一个强大的板块是os.pash,它可以完成一些针对路径名的操作。下表列举了os.pash中常用到的函数使用方法。

函数名                          使用方法
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 exists(path)                   判断指定路径(目录或文件)是否存在 isabs(path)                    判断指定路径是否为绝对路径 isdir(path)                    判断指定路径是否存在且是一个目录 isfile(path)                    判断指定路径是否存在且是一个文件 islink(path)                    判断指定路径是否存在且是一个符号链接 ismount(path)                   判断指定路径是否存在且是一个挂载点 samefile(path1, paht2)              判断path1和path2两个路径是否指向同一个文件

 

1、basename(pash)和dirname(path)

basename(pash)和dirname(path)函数分别用于获取文件名和路径名:

>>> os.path.dirname(r"a\b\test.txt")
                              
'a\\b'
>>> os.path.basename(r"a\b\test.txt")
                              
'test.txt'

 

2、join(path1[, path2[, ...]])

join()函数跟bif的那个join()函数不同,os.path.join()用于将路径名和文件名组合成一个完整的路径:

>>> os.path.join(r"c:\python34\test","fishc.txt")
                              
'c:\\python34\\test\\fishc.txt'

 

3、split(path)和splitext(path)

split()和splitext()函数都用于分割路径,split()函数分割路径和文件名(如果完全使用目录,它也会将最后一个目录作为文件名分离,且不会判断文件或者目录是否存在);splitext()函数则是用于分割文件名和扩展名:

>>> os.path.split(r"a\b\test.txt")
                              
('a\\b', 'test.txt')
>>> os.path.splitext(r"a\b\test.txt")
                              
('a\\b\\test', '.txt')

 

4、getsize(file)

getsize()函数用于获取文件的尺寸,返回值是以字节为单位:

>>> os.chdir("c:\\users\\14158\\appdata\\local\\programs\\python\\python37")
                              
>>> os.path.getsize("python.exe")
                              
99992

 

5、getatime(file)、getctime(file)和getmtime(file)

getatime(file)、getctime(file)和getmtime(file)分别用于获取文件的最近访问时间、创建时间和修改时间。不过返回值是浮点型秒数,可用time模块的gmtime()或localtime()函数换算:

>>> import time
                              
>>> temp = time.localtime(os.path.getatime("python.exe"))
                              
>>> print("python.exe被访问的时间是:",time.strftime("%d%b%y%h:%m:%s",temp))
                              
python.exe被访问的时间是: 20aug201817:46:49
>>> temp = time.localtime(os.path.getctime("python.exe"))
                              
>>> print("python.exe被创建的时间是:",time.strftime("%d%b%y%h:%m:%s",temp))
                              
python.exe被创建的时间是: 27jun201805:01:38
>>> temp = time.localtime(os.path.getmtime("python.exe"))
                              
>>> print("python.exe被修改的时间是:",time.strftime("%d%b%y%h:%m:%s",temp))
                              
python.exe被修改的时间是: 27jun201805:01:38

还有一些函数返回布尔类型的值,详情见表。

 

*******************************

三、课时30课后习题及答案

*******************************

 

 

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网