Python3.5 built-in module of the module os, sys module, shutil examples of usage analysis module

This paper describes examples Python3.5 os module built of module, sys module, shutil module usage. Share to you for your reference, as follows:
1, os Module: provides an interface to the operating system calls

#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author:ZhengzhengLiu
 
import os
print(os.getcwd())  #获取当前的操作目录,即当前Python脚本工作的目录路径
#os.chdir("F:\\PythonCode\\day5\\test")  #改变当前脚本工作目录,相当于shell下的cd
os.chdir(r"F:\PythonCode\day5\test")   #与上面一句等价(推荐使用)
print(os.getcwd())
print(os.curdir) #返回当前目录 '.'
print(os.pardir) #获取当前目录的父目录字符串名 '..'
 
os.makedirs(r"F:\a\b\c")  #生成多层递归目录
#若目录为空,则删除,并递归到上一级目录,如若也为空,则删除,依此类推
os.removedirs(r"F:\a\b\c")  #清理空文件夹
 
os.mkdir(r"F:\PythonCode\day5\t")  #生成单级目录,相当于shell中mkdir filename
os.rmdir(r"F:\PythonCode\day5\t")  #删除单级空目录,若目录不为空,无法删除或报错;相当于shell中rmdir filename
 
print(os.listdir(r"F:\PythonCode\day5\test"))  #列出指定目录下的所有文件和子目录,包括隐藏文件,并以列表方式打印
 
os.remove(r"F:\PythonCode\day5\test\1.py")  #删除一个文件
os.rename(r"F:\PythonCode\day5\test\1.py",r"F:\PythonCode\day5\test\2.py")  #重命名文件/目录
print(os.stat(r"F:\PythonCode\day5\test"))   #获取文件/目录信息
 
print(os.sep)   #输出操作系统特定的路径分隔符,win下为"\\",Linux下为"/"
print(os.linesep) #输出当前平台使用的行终止符,win下为"\r\n",Linux下为"\n"
print(os.pathsep) #输出用于分割文件路径的字符串,win下为";",Linux下为":"
print(os.environ) #查看系统的环境变量
print(os.name)   #输出字符串指示当前使用平台。win->'nt'; Linux->'posix'
print(os.system("dir")) #运行shell命令,直接显示
print(os.path.abspath(r"F:\PythonCode\day5"))  #返回path规范化的绝对路径
print(os.path.split(r"F:\PythonCode\day5\test\1.py")) #将path分割成目录和文件名二元组返回
print(os.path.dirname(r"F:\PythonCode\day5"))  #返回path的目录。其实就是os.path.split(path)的第一个元素
print(os.path.basename(r"F:\PythonCode\day5"))  #返回path最后的文件名。如何path以/或\结尾,那么就会返回空值。
print(os.path.exists(r"F:\PythonCode\day5"))  #如果path存在,返回True;如果path不存在,返回False
print(os.path.isabs(r"F:\PythonCode\day5"))  #如果path是绝对路径,返回True
print(os.path.isfile(r"F:\PythonCode\day5\p_test.py"))  #如果path是一个存在的文件,返回True,否则返回False
print(os.path.isdir(r"F:\PythonCode\day5"))  #如果path是一个存在的目录,则返回True。否则返回False
print(os.path.join(r"F:",r"\PythonCode",r"\day5",r"\day"))  #将多个路径组合后返回,第一个绝对路径之前的参数将被忽略
print(os.path.getatime(r"F:\PythonCode\day5"))  #返回path所指向的文件或者目录的最后存取时间
print(os.path.getmtime(r"F:\PythonCode\day5"))  #返回path所指向的文件或者目录的最后修改时间

operation result:

F:\PythonCode\day5
F:\PythonCode\day5\test
.
..
['2.py', 'module_test.py', 'test.py']
os.stat_result(st_mode=16895, st_ino=8162774324625191, st_dev=104211, st_nlink=1, st_uid=0, st_gid=0, st_size=4096, st_atime=1506609480, st_mtime=1506609480, st_ctime=1506579769)
\
 
 
;
environ({'PROCESSOR_LEVEL': '6', 'WINDOWS_TRACING_LOGFILE': 'C:\\BVTBin\\Tests\\installpackage\\csilogfile.log', 'PROCESSOR_ARCHITECTURE': 'x86')
nt
 ������ F �еľ��� ѧϰ��
 �������� 0001-9713
 
 F:\PythonCode\day5\test ��Ŀ¼
 
2017/09/28 22:38  <DIR>     .
2017/09/28 22:38  <DIR>     ..
2017/09/28 22:37        69 2.py
2017/09/28 14:31        121 module_test.py
2017/09/28 14:35        237 test.py
        3 ���ļ�      427 �ֽ�
        2 ��Ŀ¼ 14,051,733,504 �����ֽ�
0
F:\PythonCode\day5
('F:\\PythonCode\\day5\\test', '1.py')
F:\PythonCode
day5
True
True
True
True
F:\day
1506656912.210523
1506656912.210523

2, sys module

#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author:ZhengzhengLiu
 
import sys
print(sys.argv)   #命令行参数List,第一个元素是程序本身路径
print(sys.version) #获取Python解释程序的版本信息
print(sys.path)   #返回模块的搜索路径,初始化时使用PYTHONPATH环境变量的值
print(sys.platform) #返回操作系统平台名称
sys.stdout.write('please:')  #标准输出,写入字符串输出到屏幕
val = sys.stdin.readline()[:-1]  #标准输入
print(val)
sys.exit(0)     #退出程序,正常退出时exit(0)

operation result:

['F:/PythonCode/day5/sys_module.py']
3.5.2 |Anaconda 4.2.0 (32-bit)| (default, Jul 5 2016, 11:45:57) [MSC v.1900 32 bit (Intel)]
['F:\\PythonCode\\day5', 'F:\\PythonCode', 'C:\\Users\\Administrator\\Anaconda3\\python35.zip', 'C:\\Users\\Administrator\\Anaconda3\\DLLs', 'C:\\Users\\Administrator\\Anaconda3\\lib', 'C:\\Users\\Administrator\\Anaconda3', 'C:\\Users\\Administrator\\Anaconda3\\lib\\site-packages', 'C:\\Users\\Administrator\\Anaconda3\\lib\\site-packages\\Sphinx-1.4.6-py3.5.egg', 'C:\\Users\\Administrator\\Anaconda3\\lib\\site-packages\\win32', 'C:\\Users\\Administrator\\Anaconda3\\lib\\site-packages\\win32\\lib', 'C:\\Users\\Administrator\\Anaconda3\\lib\\site-packages\\Pythonwin', 'C:\\Users\\Administrator\\Anaconda3\\lib\\site-packages\\setuptools-27.2.0-py3.5.egg']
win32
hello
please:hello

3, shutil module: Advanced files, folders, archive processing module

(1) copy the contents of the file to another file, can be part of --shutil.copyfileobj (fsrc, fdst [, length ])
Run Results: Here Insert Picture Description
(2) copies of documents --shutil.copyfile (src, dst)

import shutil
shutil.copyfile("p1.py","p2.py")  #拷贝文件

Operating results: Here Insert Picture Description
(3) only copy rights (content, groups, users remain unchanged) - shutil.copymode (src, dst)

Information (4) copy status, comprising: mode bits, atime, mtime, flags - shutil.copystat (src, dst)

(5) copies of documents and permissions --shutil.copy (src, dst)

(6) copy files and state information --shutil.copy2 (src, dst)

(7) recursively to copy files:

shutil.ignore_patterns(*patterns)
shutil.copytree(src, dst, symlinks=False, ignore=None)
import shutil
shutil.copytree("test","test1")  #递归的去拷贝文件

The result:
Here Insert Picture Description
(8) to recursively delete files --shutil.rmtree (path [, ignore_errors [, onerror]])

(9) to move files recursively --shutil.move (src, dst)

(10) to create a compressed package and return the file path, such as: zip, tar - shutil.make_archive (base_name, format, ...)

base_name: archive file name, it can be compressed path. Just when the file name is saved to the current directory, or saved to a specified location,
such as: www => Save to the current path
, such as: / Users / wupeiqi / www = > Save to / the Users / wupeiqi /
format: compressed packet type. " ZIP "," the tar "," bztar "," gztar "
ROOT_DIR: to compress folder path (current default directory)
owner: the user, the default current user
group: group, default current set
logger: for logging, usually logging.Logger objects

import shutil
shutil.make_archive("shutil_archive_test","zip","F:\PythonCode\day5")

The result: Here Insert Picture Description
summary: shutil handling compressed package is to call ZipFile and TarFile two modules carried out

import zipfile
z = zipfile.ZipFile("day5.zip","w")
z.write("p1.py")
print("===========")
z.write("p2.py")
z.close()

operation result:

===========

Here Insert Picture Description
We recommend the python learning sites, click to enter, to see how old the program is to learn! From basic python script, reptiles, django, data mining, programming techniques, work experience, as well as senior careful study of small python partners to combat finishing zero-based information projects! The method every day to explain the timing of Python programmers technology, to share some of the learning and the need to pay attention to the small details add a linker script

Published 30 original articles · won praise 10 · views 40000 +

Guess you like

Origin blog.csdn.net/haoxun06/article/details/104485221