A, time \ datetime Module
1, le temps est divisé en trois formats:
1, l'horodatage: de 1970 au nombre actuel de secondes se sont écoulées
effet: pour calculer l'intervalle de temps
print(time.time()) # 1585554811.0685697
2, selon un certain format du temps: 30/03/2020 11:11:11
Rôle: Temps d'affichage
print(time.strftime('%Y-%m-%d %H:%M:%S %p')) # 年月日 时分秒 时间段 2020-03-30 15:56:39 PM
print(time.strftime('%Y-%m-%d %X')) # 年月日,时分秒
3, la structure temporelle de la
mesure: une partie d'acquisition de temps seul
res = time.localtime()
print(res)
print(res.tm_year)
print(res.tm_yday)
二: datetime
import datetime
print(datetime.datetime.now()) # 2020-03-30 16:18:25.157068
print(datetime.datetime.now() + datetime.timedelta(days=3)) # 2020-04-02 16:18:25.157068
print(datetime.datetime.now() + datetime.timedelta(weeks=1)) # 2020-04-06 16:18:25.157068
2, le temps nécessaire pour maîtriser le fonctionnement du module
1, le temps de conversion de format
struct_time-> horodatages
s_time=time.localtime()
print(s_time)
print(time.mktime(s_time))
Timestamp -> struct_time
tp_time=time.time()
print(time.localtime(tp_time))
Ajouté: temps universel coordonné et l'heure locale
print(time.localtime())
print(time.gmtime()) # 世界标准时间,了解
print(time.localtime(333333333))
print(time.gmtime(333333333))
struct_time-> temps de chaîne formatée
s_time=time.localtime()
print(time.strftime('%Y-%m-%d %H:%M:%S',s_time))
print(time.strptime('1988-03-03 11:11:11','%Y-%m-%d %H:%M:%S'))
Mise au point besoin de maîtriser
format string--->struct_time--->timestamp
struct_time=time.strptime('1988-03-03 11:11:11','%Y-%m-%d %H:%M:%S')
timestamp=time.mktime(struct_time)+7*86400
print(timestamp)
format string<---struct_time<---timestamp
res=time.strftime('%Y-%m-%d %X',time.localtime(timestamp))
print(res)
graphique:
connaissance des
import time
print(time.asctime())
import datetime
print(datetime.datetime.now()) # 北京时间
print(datetime.datetime.utcnow()) # 世界标准时间
print(datetime.datetime.fromtimestamp(333333)) # 它不能选择输出顺序,只能年月日 分时秒
Deux, le module aléatoire
1, les points de connaissances
import random
print(random.random()) #(0,1)----float 大于0且小于1之间的小数
print(random.randint(1, 3)) # [1,3] 大于等于1且小于等于3之间的整数
print(random.randrange(1, 3)) # [1,3) 大于等于1且小于3之间的整数
print(random.choice([111, 'aaa', [4, 5]])) # 1或者23或者[4,5]
print(random.sample([111, 'aaa', 'ccc','ddd'],2)) # 列表元素任意2个组合
print(random.uniform(1, 3)) # 大于1小于3的小数,如1.927109612082716
item = [1, 3, 5, 7, 9]
random.shuffle(item) # 打乱item的顺序,相当于"洗牌"
print(item)
2, l'application: codes aléatoires
"""
实现思想:
import random
res=''
for i in range(6):
从26大写字母中随机取出一个=chr(random.randint(65,90))
从10个数字中随机取出一个=str(random.randint(0,9))
从26小写字母中随机取出一个=chr(random.randint(97,122))
随机字符=random.choice([从26大写字母中随机取出一个,从10个数字中随机取出一个])
res+=随机字符
"""
import random
def make_code(size=4):
res=''
for i in range(size):
s1=chr(random.randint(65,90))
s2=str(random.randint(0,9))
s3=chr(random.randint(97,122))
print(res)
return res
print(make_code(6))
Trois, module os
1, des commandes communes
"""
os.getcwd() 获取当前工作目录,即当前python脚本工作的目录路径
os.chdir("dirname") 改变当前脚本工作目录;相当于shell下cd
os.curdir 返回当前目录: ('.')
os.pardir 获取当前目录的父目录字符串名:('..')
os.makedirs('dirname1/dirname2') 可生成多层递归目录
os.removedirs('dirname1') 若目录为空,则删除,并递归到上一级目录,如若也为空,则删除,依此类推
os.mkdir('dirname') 生成单级目录;相当于shell中mkdir dirname
os.rmdir('dirname') 删除单级空目录,若目录不为空则无法删除,报错;相当于shell中rmdir dirname
os.listdir('dirname') 列出指定目录下的所有文件和子目录,包括隐藏文件,并以列表方式打印
os.remove() 删除一个文件
os.rename("oldname","newname") 重命名文件/目录
os.stat('path/filename') 获取文件/目录信息
os.sep 输出操作系统特定的路径分隔符,win下为"\\",Linux下为"/"
os.linesep 输出当前平台使用的行终止符,win下为"\r\n",Linux下为"\n"
os.pathsep 输出用于分割文件路径的字符串 win7下为;,Linux下为:
os.name 输出字符串指示当前使用平台。win->'nt'; Linux->'posix'
os.system("bash command") 运行shell命令,直接显示
os.environ 获取系统环境变量
"""
2, utiliser la commande
1, pour obtenir une taille d'un dossier et tous les sous-dossiers et le nom du sous-dossiers et afficher les fichiers correspondants
res=os.listdir('.')
print(res) # ['note.py']
size=os.path.getsize(r'/Users/linhaifeng/PycharmProjects/s14/day22/01 时间模块.py')
print(size) # 2346
2, les informations de fichier d'impression et changement de nom
os.system('dir E:\\Python学习相关') # 打印文件夹下的文件信息
os.rename('old_name', 'new_name') # 重命名文件夹/目录
3, fonction environ: clé et la valeur doit être spécifiée sont des chaînes
os.environ['aaa']='111' # 某个位置登录用户,通过用户依据去数据库文件查找信息
print(os.environ) # 返回值是一个字典
PATH # 在执行系统命令的时候用它
sys.path # 在导模块的时候才会使用它
4, la série de os.path (※※※※※)
"""
os.path.abspath(path) 返回path规范化的绝对路径
os.path.split(path) 将path分割成目录和文件名二元组返回
os.path.dirname(path) 返回path的目录。其实就是os.path.split(path)的第一个元素
os.path.basename(path) 返回path最后的文件名。如何path以/或\结尾,那么就会返回空值。即os.path.split(path)的第二个元素
os.path.exists(path) 如果path存在,返回True;如果path不存在,返回False
os.path.isabs(path) 如果path是绝对路径,返回True
os.path.isfile(path) 如果path是一个存在的文件,返回True。否则返回False
os.path.isdir(path) 如果path是一个存在的目录,则返回True。否则返回False
os.path.join(path1[, path2[, ...]]) 将多个路径组合后返回,第一个绝对路径之前的参数将被忽略
os.path.getatime(path) 返回path所指向的文件或者目录的最后存取时间
os.path.getmtime(path) 返回path所指向的文件或者目录的最后修改时间
os.path.getsize(path) 返回path的大
os.path.abspath(path) 返回path规范化的绝对路径
os.path.split(path) 将path分割成目录和文件名二元组返回
os.path.dirname(path) 返回path的目录。其实就是os.path.split(path)的第一个元素
os.path.basename(path) 返回path最后的文件名。如何path以/或\结尾,那么就会返回空值。即os.path.split(path)的第二个元素
os.path.exists(path) 如果path存在,返回True;如果path不存在,返回False
os.path.isabs(path) 如果path是绝对路径,返回True
os.path.isfile(path) 如果path是一个存在的文件,返回True。否则返回False
os.path.isdir(path) 如果path是一个存在的目录,则返回True。否则返回False
os.path.join(path1[, path2[, ...]]) 将多个路径组合后返回,第一个绝对路径之前的参数将被忽略
os.path.getatime(path) 返回path所指向的文件或者目录的最后存取时间
os.path.getmtime(path) 返回path所指向的文件或者目录的最后修改时间
os.path.getsize(path) 返回path的大小
"""
5, les dispositions du répertoire racine
# 推荐用这种
BASE_DIR=os.path.dirname(os.path.dirname(__file__))
print(BASE_DIR)
BASE_DIR=os.path.normpath(os.path.join(
__file__,
'..',
'..'
))
print(BASE_DIR)
6, après python3.5, a lancé un nouveau module pathlib
from pathlib import Path
res = Path(__file__).parent.parent
print(res)
res=Path('/a/b/c') / 'd/e.txt'
print(res) # \a\b\c\d\e.txt
print(res.resolve()) # F:\a\b\c\d\e.txt
Quatre, le module sys
1, des commandes communes
sys.argv # 命令行参数List,第一个元素是程序本身路径
sys.exit(n) # 退出程序,正常退出时exit(0)
sys.version # 获取Python解释程序的版本信息
sys.maxint # 最大的Int值
sys.path # 返回模块的搜索路径,初始化时使用PYTHONPATH环境变量的值
sys.platform # 返回操作系统平台名称
2, l'utilisation sys.argv
import sys
# python3 note.py 1 2 3
# sys.argv 获取的是解释器后的参数值
print(sys.argv) # ['note.py', '1', '2', '3']
3, copie de fichier
src_file = sys.argv[1]
dst_file = sys.argv[2]
with open(r'%s'%src_file, mode='rb') as read_f,\
open(r'%s'%dst_file, mode='wb') as write_f:
for line in read_f:
write_f.write(line)
Cinq, le module shutil
fichiers supérieurs, dossiers, module de traitement des archives
shutil.copyfileobj (CSRP, FDST [, longueur
]) copie le contenu du fichier dans un autre fichier
import shutil
shutil.copyfileobj(open('old.xml','r'), open('new.xml', 'w'))
shutil.copyfile (src, dst)
copies de documents
shutil.copyfile('f1.log', 'f2.log') #目标文件无需存在
shutil.copymode (src, dst)
copie seulement des droits. Contenu, les groupes, les utilisateurs restent inchangés
shutil.copymode('f1.log', 'f2.log') #目标文件必须存在
shutil.copystat (src, dst)
seulement copier les informations d'état, comprenant: des bits de mode, atime, mtime, drapeaux
shutil.copystat('f1.log', 'f2.log') #目标文件必须存在
shutil.copy (src, dst)
pour copier des fichiers et des autorisations
import shutil
shutil.copy('f1.log', 'f2.log')
shutil.copy2 (src, dst)
copier des fichiers et des informations d'état
import shutil
shutil.copy2('f1.log', 'f2.log')
shutil.ignore_patterns (* Modèles)
shutil.copytree (src, DST, = False liens symboliques, l'ignorer = Aucun)
récursive copiés dans le dossier
import shutil
shutil.copytree('folder1', 'folder2', ignore=shutil.ignore_patterns('*.pyc', 'tmp*'))
# 目标目录不能存在,注意对folder2目录父级目录要有可写权限,ignore的意思是排除
shutil.rmtree (chemin [, ignore_errors [,
onerror]]) récursive à supprimer des fichiers
import shutil
shutil.rmtree('folder1')
shutil.move (src, dst)
récursivement pour déplacer un fichier, qui est semblable commande mv, en fait, renommé.
import shutil
shutil.move('folder1', 'folder3')
shutil.make_archive (base_name, le format, ...)
Créer un package compressé et retourner le chemin du fichier, par exemple: zip, tar
Créer un package compressé et retourner le chemin du fichier, par exemple: zip, tar
- nom_base: nom de fichier archive, il peut être compressé chemin. Juste au moment où le nom de fichier est enregistré dans le répertoire courant, ou enregistré dans un emplacement spécifié,
tel que data_bak => pour enregistrer le chemin en cours
, tels que: / tmp / data_bak => Enregistrer / tmp / - Format: type de paquet compressé, "zip", "goudron", "bztar", "gztar"
- root_dir: Pour compresser le chemin du dossier (le répertoire courant par défaut)
- propriétaire: l'utilisateur, l'utilisateur par défaut
- groupe: groupe, par défaut, le groupe actuel
- Enregistreur: pour l'enregistrement, l'objet est généralement logging.Logger
#将 /data 下的文件打包放置当前程序目录
import shutil
ret = shutil.make_archive("data_bak", 'gztar', root_dir='/data')
#将 /data下的文件打包放置 /tmp/目录
import shutil
ret = shutil.make_archive("/tmp/data_bak", 'gztar', root_dir='/data')