概述
这个模块提供了很多简单方便的方式去调用操作系统开放的功能,至于更高维度的文件,文件夹操作的方法需要参考 shutil 这个模块
在python中,文件名字,命令行参数,环境变量都是字符串。因此一些系统的字符转换就是必须的。可以使用 sys.getfilesystemencoding() 查看系统编码
系统
os.environ
返回环境变量
os.getenv(key)
得到key值的环境变量
os.uname()
相当于Linux的uname,得到系统的信息
1 2
| >>> os.uname() ('Linux', 'VM_16_8_centos', '3.10.0-514.26.2.el7.x86_64', '#1 SMP Tue Jul 4 15:04:05 UTC 2017', 'x86_64')
|
os.getuid
os.getgroups()
返回当前进程相关的group
os.getlogin()
得到当前登录的用户
os.popen(cmd,mode=‘r’,buffering=-1)
执行系统级别的命令,但是没有输出。 mode有 read和write两种模式。 但是常见的还是subprocess这个命令
1 2 3 4
| import os with os.popen('git clone https://github.com/zhuzhuyule/img_to_txt.git')as f: a = f.read() print(a)
|
文件夹操作
os.mkdir(path)
创建一个文件夹
os.rmdir(path)
移除文件夹
os.makedirs(path)
创建一系列文件夹
1
| os.makedirs('test/test/test')
|
os.removedirs(path)
移除文件夹,包括子文件夹. 递归移除.如下,先移除最里面的test,然后是外层的test,最后在移除最外面的test
1
| os.removedirs('test/test/test')
|
os.chdir(path)
变换路径
文件
os.listdir(path)
列出当前文件夹下面的所有文件和文件夹
os.scandir(path)
扫描当前路径下面的所有文件和文件夹,返回一个DirEntry对象。有以下属性
- name
- path
- is_file
- is_dir
- inode
- is_symlink
os.remove(path)
path是文件的路径,注意,一定得是文件才能够删除。文件夹不能这样删
os.rename(src,dst)
在Unix 中,如果dst是个已经存在的文件,如果用户有权限,那么该文件会被没有提示的替换
在windows中,如果dst已经存在,那么就会出错,即使dst是个文件,而不是文件夹
rename具有移动文件夹(无论文件夹里面是否有文件),并且重命名的功能
1 2 3
| >>> os.rename("d://New","d://new_folder") # 重命名 >>> os.rename("d://new_folder","new_folder2") # 将文件夹移动到当前目录并且改名 >>> os.renmae("new_folder2","d://new_folder") # 文件夹里面还有文件,也可以移动+改名
|
os.renames(old,new)
将old层级文件夹全部改名为new的层级文件夹
1 2 3 4 5
| >>> os.renames("d://new_folder2//test2//test2.txt","d://new_folder2//test1//test1.txt") 此时 test2 文件夹会变成test1文件夹, test2.txt 会变成test1.txt 而与rename不同的是: rename如果test2文件夹不存在,就会出错。(但是如果文件夹存在就不会出错) rename是不会出错的。不管文件夹存不存在。但是如果文件夹之前存在,他就会被改名消失。除非这个文件夹里面还有其他东西,这样这个文件夹就不会被改名消失。
|
os.walk(path)
返回一个generator对象,分别有三个值: root, dirs, files,
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
| root : 返回当前路径下所有文件夹的路径,字符串 dirs: 返回一个list,返回当前路径下的文件夹名称,如果子文件夹还有文件夹,返回另外一个list files: 返回list,类似dirs,只不过返回的是文件名。
>>> for root,dirs,files in os.walk("d://new_folder2//"): print("files: ",files) print("root: ",root) print("dirs: ",dirs)
files: ['test.txt'] root: d://new_folder2// dirs: ['test1', 'test2'] files: ['test1.txt'] root: d://new_folder2//test1 dirs: [] files: ['test2.txt', 'testsample.txt'] root: d://new_folder2//test2 dirs: ['teste233'] files: [] root: d://new_folder2//test2\teste233 dirs: []
|
os.replace()
这个是跨平台的os.rename
1 2 3 4 5 6 7 8 9 10 11
| # test1 是存在的文件夹 #os.replace('D://new_folder2//test2/test2.txt',"D://new_folder2//test1//test21.txt")
# test5 是不存在的文件夹, 失败 #os.replace('D://new_folder2//test4/test1.txt',"D://new_folder2//test5//test51.txt")
#成功 #os.replace('D://new_folder2//test1',"D://new_folder2//test4")
# 成功 # os.renames('D://new_folder2//test1/test21.txt',"D://new_folder2//test3//test21.txt")
|