Common modules in Python-OS and time modules

Foreword:

Author: God’s child is singing
This is the notes
I took while listening to the teacher’s lecture. Hello, everyone. My name is Chen Yunzhi . You can call me Xiaozhi . Please visit the homepage to add friends.

Module

1. Module introduction

Simple understanding : It is equivalent to a toolkit , which is a py file that encapsulates a bunch of functions . If you use a certain function, you can call this package. You don't need to write a bunch of code yourself.

Import method
(1) import 模块
(2) Import functions in the modulefrom 模块 import 函数

Note : The module must be in the current directory when importing

Get alias as: module name is too long, you can get alias through as

2. Common modules

2.1 os module

  1. Function : often used to rename, delete, obtain path and other operations on files

For example, I created a test folder on the d drive

Insert picture description here


Code exercise:

import  os
import shutil
#os.rename('text_备份2.txt','text_重命名.txt')#重命名文件
#os.remove('文件名')#删除文件,如果不存在就会报错
#os.mkdir('textCJ')#创建文件夹
#os.rmdir('textCJ')#删除文件夹,只能删除空目录
#os.mkdir('d:/python编程')#在D盘下创建文件夹,还可以一级级创建/,不能连续创建
#os.rmdir('d:/python编程')
#os.makedirs('d:/p/d/f')#多级文件创建
#shutil.rmtree('d:p/d/f')#删除非空目录文件shutil

print('当前路径:',os.getcwd())#获取当前目录
#print(os.path)
#os.path.join(os.path.join(os.getcwd(),'第十一天'))#路径拼接

#获取python中的目录列表,老版本
#print(os.listdir('d:/'))
print('*'*15)
#新版本
with os.scandir('D:/test/') as f:#scandir和with一起使用,上下文管理器会在迭代器遍历完成后自动释放资源
    for item in f:
        print(item.name)
print('*'*15)
f='D:/test/'
for item in os.listdir(f):
    if os.path.isfile(os.path.join(f,item)):#判断文件,.isdir是判断目录
        print('只输出文件:',item)
Insert picture description here


2. Basic operation commands

methodExplanation
os.getcwd()Get the current working directory, that is, the directory path where the current python script works
os.chdir("dirname")Change the working directory of the current script; equivalent to cd in the shell
os.curdirReturn to the current directory: ('.')
os.pardirGet the string name of the parent directory of the current directory: ('...')
os.makedirs('dir1/dir2')Can generate multi-layer recursive directories
os.removedirs('dirname1')If the directory is empty, delete it and recursively to the upper-level directory, if it is also empty, delete it, and so on
os.mkdir('dirname')Generate a single-level directory; equivalent to mkdir dirname in the shell
os.rmdir('dirname')Delete a single-level empty directory, if the directory is not empty, it cannot be deleted, and an error is reported
os.listdir('dirname')List all files and subdirectories in the specified directory, including hidden files, and print them in a list
os.remove()Delete a file
os.rename("oldname","new")Rename file/directory
os.stat('path/filename')Get file/directory information
os.sepOperating system specific path separator, "\" under win, "/" under Linux
os.linesepThe line terminator used by the current platform, "\t\n" under win, "\n" under Linux
os.pathsepThe string used to split the file path
os.nameThe string indicates the platform currently in use. win->'nt'; Linux->'posix'
os.system("bash command")Run the shell command and display directly
os.environGet system environment variables
os.path.abspath(path)Return the normalized absolute path of path
os.path.split(path)Split path into a two-tuple of directory and file name and return
os.path.dirname(path)Return the directory of path. In fact, it is the first element of os.path.split(path)
os.path.basename(path)Returns the file name at the end of path. If the path ends with / or \, then a null value will be returned. That is, the second element of os.path.split(path)
os.path.exists(path)If path exists, return True; if path does not exist, return False
os.path.isabs(path)If path is an absolute path, return True
os.path.isfile(path)If path is an existing file, return True. Otherwise return False
os.path.isdir(path)If path is an existing directory, it returns True. Otherwise return False
os.path.join(path1[, path2[, …]])Combine multiple paths and return, the parameters before the first absolute path will be ignored
os.path.getatime(path)Returns the last access time of the file or directory pointed to by path
os.path.getmtime(path)Returns the last modification time of the file or directory pointed to by path

2.2 time, datetime module

  1. time module
import time 
time.sleep(6) # 程序暂停6s
print(time.time())#获取时间戳
print(time.localtime())#获取本地时间
print(time.strftime("%Y-%m-%d %H:%M:%S 星期%w",time.localtime()))#格式化输出

Output:

Insert picture description here


time formatting symbol

  • %b local simplified month name
  • %B local full month name
  • %c local corresponding date and time representation
  • %j day of the year (001-366)
  • %p is the equivalent of local AM or PM
  • %U Week number of the year (00-53) Sunday is the beginning of the week
  • %w week (0-6), Sunday is the beginning of the week
  • %W Week number of the year (00-53) Monday is the start of the week
  • %x local corresponding date representation
  • %X local corresponding time representation
  • %Z The name of the current time zone
  • %%% sign itself
  1. datatime module
Mainly used for time calculation
datetime.date.fromtimestamp(time.time())#装换时间戳
#输出:2021-06-03

Add and subtract time calculation

import datetime
print(datetime.datetime.now())
#当前时间加上1天2小时30分.
print(datetime.datetime.now() + datetime.timedelta(days=1,hours=2,minutes=30))

Output:

2021-06-05 10:32:40.462593
2021-06-06 13:02:40.462593
My blog: https://blog.csdn.net/weixin_46654114
Reprint instructions: Tell me, be sure to indicate the source, and attach my blog link.

Please give me a thumbs up and encourage me

Insert picture description here