Common modules in Python-OS and time modules


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.


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


with os.scandir('D:/test/') as f:#scandir和with一起使用,上下文管理器会在迭代器遍历完成后自动释放资源
    for item in f:
for item in os.listdir(f):
    if os.path.isfile(os.path.join(f,item)):#判断文件,.isdir是判断目录
Insert picture description here

2. Basic operation commands

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.strftime("%Y-%m-%d %H:%M:%S 星期%w",time.localtime()))#格式化输出


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装换时间戳

Add and subtract time calculation

import datetime
print( + datetime.timedelta(days=1,hours=2,minutes=30))


2021-06-05 10:32:40.462593
2021-06-06 13:02:40.462593
My blog:
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