Python module accumulation

Liu Changdong 2021-11-25 18:50:07
python module accumulation

1. import random random number

 # -*- coding: UTF-8 -*-
import random
print( random.randint(1,10) ) # produce 1 To 10 A random number of integer type
print( random.random() ) # produce 0 To 1 Between random floating-point numbers
print( random.uniform(1.1,5.4) ) # produce 1.1 To 5.4 Between random floating-point numbers , Interval can not be an integer
print( random.choice('tomorrow') ) # Randomly select an element from the sequence
print( random.randrange(1,100,2) ) # Generated from 1 To 100 The interval is 2 Random integer of
print random.sample('zyxwvutsrqponmlkjihgfedcba',5) # Generates a specified number of random characters from multiple characters :
ran_str = ''.join(random.sample(string.ascii_letters + string.digits, 8))# from a-zA-Z0-9 Generates a specified number of random characters :
items = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0] # Disorganize the order
print random.shuffle(items)

2.os Basics

2.1 Catalog related

os.chdir(path) # Change the current working directory
os.getcwd() # Directory path Current working directory
os.listdir(path) # View content amount to dir
os.mkdir(path[, mode]) # newly build amount to md
## Generally speaking First judge Is there any New again
if not os.path.exists(" New folder test "):
os.mkdir(" New folder test ")
os.open(file, flags[, mode]) # Open a file

2.2 Delete

os.rmdir(path) # Delete empty folder
os.unlink(path) # Delete file path link And documents

os.remove(path) # Delete file The preferred
remove Than unlink There are multiple functions to delete directories , When deleting files ,remove and unlink The function of is the same ==
When remove() For directory , Equivalent to calling rmdir Delete directory ,
When remove() For files , Equivalent to calling unlink Delete file link
oos.removedirs(path) # Recursive delete Folder

2.3 rename os.renames(path)

os.rename("/tmp/test/test2","/tmp/test1/test3") # xxx Only for the last file ( Or folder ) rename
os.renames("/tmp/test/test2","/tmp/test1/test3" # √ √ √ For both files and folders rename

2.4 os.stat(path) # Return to read the relevant properties of the specified file , utilize stat Module processing .

os.stat(path).st_mtime # Creation time
os.stat(path).st_size # File size

2.4.1 About file size os.stat(path).st_size and os.path.getsize(path)

 If you want to achieve optimal performance , Use os.stat() First check whether the path is a file , Call again st_size .
If you want to use it os.path.getsize() , Must be used in advance os.path.isfile() Decide if it's a document , Reuse .

os.utime(path, times) # return designated path File access and modification time .

2.5 os.path() modular

os.path.basename(path) Return the filename
os.path.dirname(path) Return file path

== # Return path ==
path=os.path
print(path)
Output <module ‘ntpath’ from ‘C:\Users\GPCC\AppData\Local\Programs\Python\Python310\lib\ntpath.py’>

os.path.isfile(path) Determine whether the path is a file
os.path.isdir(path) Determine whether the path is a directory

2.5.1 Division \ Combined path

os.path.join(path1[, path2[, ...]]) Combine directory and filename into a path
os.path.split(path) Divide the path into dirname and basename, Returns a tuple
os.path.splitdrive(path) Generally used in windows Next , Returns a tuple of drive names and paths
os.path.splitext(path) Split the path , Returns tuples of pathnames and file extensions
os.path.splitunc(path) Divide the path into load points and files

2.5.2 Access time

os.path.getatime(path) Return to the most recent visit time ( Floating point seconds )
os.path.getmtime(path) Return the latest file modification time
os.path.getctime(path) Return file path Creation time
os.path.getsize(path) Return file size , Returns an error if the file does not exist

2.6 os.shutil Additions and deletions ( Sutley )

  • newly build

     if not os.path.exists(" New folder " ):
    os.mkdir(" New folder "")
    
  • Copy

    shutil.copy(“ file name ”,“ Destination folder / New file name ”)

  • Move

     shutil.move(" file name "," Destination folder ")
    
  • Delete

     shutil.rmtree(" Folder ")
    os.remove(" Folder ")
    

3. golb Traverse files and folders

import glob
import os
print(glob.glob("**")) # In the current directory Documents and folders No subdirectories 
print(glob.glob("**/")) # Subdirectory folder 
print(glob.glob("**/**")) # Subdirectory files and files 
print(glob.glob("**/",recursive=True)) # Subdirectory folder Same list 
print(glob.glob("**",recursive=True)) # In the current directory Documents and folders + Subdirectory files and files Same list 
print(glob.glob("**/*.py",recursive=True)) # Under current directory be known as *.py The file of 
print(glob.glob("*/*.py",recursive=True)) # only In subfolders be known as *.py The file of 

4. datetime Date time dependent

4.1 datetime

print(datetime.datetime.now()) #2021-11-09 08:29:16.506862
print(datetime.datetime.now().date()) #2021-11-09
print(datetime.datetime.now().time()) #08:29:51.379761
print(datetime.datetime.now().day) # 9 year month hour min minute

4.2 Time difference

  • The difference between the two dates

     date1=datetime.date(2018,5,6) # Date format
    print(datetime.datetime.now().date()-date1)
    
  • 0000 Year to date

     print(datetime.date.today().toordinal())
    12254
    

4.3 Time format

  • Time format

     t=datetime.date(2018,5,6)
    print(t.strftime("%y-%m-%d %H:%M:%S"))
    #18-05-06 00:00:00
    
版权声明
本文为[Liu Changdong]所创,转载请带上原文链接,感谢
https://pythonmana.com/2021/11/20211109102710674y.html

  1. 关于#python_while循环的写法#的问题,如何解决?
  2. Python异常处理中异常的种类有哪些?你知道几个?
  3. Python异常處理中异常的種類有哪些?你知道幾個?
  4. Quels sont les types d'exceptions dans la gestion des exceptions python? Combien en savez - vous?
  5. À propos de # Python Comment résoudre le problème de l'écriture de la Boucle while?
  6. Python如何操作system.data.sqlite数据库
  7. python数字游戏,让你欲罢不能
  8. Python中的可迭代对象、迭代器、For循环工作机制、生成器
  9. 一个从没接触过编程的人,如何自学进入Python行业?
  10. 一份超级实用的 Python ”技巧“清单
  11. Python 程序员给上路初学者的3点忠告
  12. 3 conseils pour les débutants sur la route par les programmeurs Python
  13. Une liste de conseils Python super pratiques
  14. Comment quelqu'un qui n'a jamais été en contact avec la programmation peut - il apprendre à entrer dans l'industrie python?
  15. Objets itérables, itérateurs, pour le mécanisme de travail circulaire, générateurs en python
  16. Les Jeux de chiffres Python vous font vous arrêter
  17. Comment Python fonctionne avec la base de données system.data.sqlite
  18. Python之html与markdown互相转换
  19. Python之html與markdown互相轉換
  20. Conversion HTML et markdown de Python
  21. Python生成的随机数,要怎么设定成随机数a小于随机数b啊
  22. Python生成的隨機數,要怎麼設定成隨機數a小於隨機數b啊
  23. Le nombre aléatoire généré par Python, comment définir le nombre aléatoire a est inférieur au nombre aléatoire B
  24. Python爬虫能做什么
  25. Python老技师给上路初学者的3点忠告
  26. 3 conseils aux débutants sur la route de l'ancien technicien Python
  27. Que peuvent faire les reptiles Python
  28. The code NPM cloned from git will report a python error after it is installed!
  29. 数据分析从零开始实战,Pandas读写CSV数据
  30. Python基础(十二):类与对象
  31. Python Foundation (12): classes et objets
  32. Python基礎(十二):類與對象
  33. L'analyse des données commence à zéro et pandas lit et écrit les données CSV
  34. Python Qt GUI设计:QSlider滑动条类(基础篇—16)
  35. #yyds干货盘点#数据分析从零开始实战,Pandas读写CSV数据
  36. This paper designs an examination system for automatically setting questions and judging papers by using Python standard library language to investigate the ability of users to calculate four integers within 100.
  37. Yyds Dry Inventory # Data Analysis started from zero, pandas read and write CSV Data
  38. python数据结构:数组、列表、栈、队列及实现
  39. Python编程真的是未来人工智能的主流吗?
  40. Python编写通讯录,支持模糊查询,利用数据库存储
  41. Python編寫通訊錄,支持模糊查詢,利用數據庫存儲
  42. Python編程真的是未來人工智能的主流嗎?
  43. Python écrit le carnet d'adresses, prend en charge les requêtes floues et utilise le stockage de base de données
  44. La programmation Python est - elle vraiment le courant dominant de l'IA future?
  45. Structure des données Python: tableaux, listes, piles, files d'attente et implémentations
  46. Python networkx Practical Social Network Visualization
  47. [译] 通过 for 循环,比较 Python 与 Ruby 编程思想的差别
  48. Comparez les différences de programmation entre Python et Ruby à travers la boucle for
  49. Python basic and introductory tutorials
  50. What you don't know
  51. 人生苦短,能让你更早下班的Python垃圾回收机制
  52. Boring playing Tetris, using Python to do their own without advertising
  53. Seemingly boring Python games, but I fished for work all afternoon!!
  54. A collection of grammar knowledge points for getting started with Python
  55. Benefits of learning Python
  56. Play childhood memories with Python, greedy snake
  57. Python is suitable for beginners
  58. Simple Python game making
  59. Welfare is coming!! Python basic syntax dry goods
  60. Simply understand the learning direction of Python and make yourself a better choice