常用模块

常用模块

  • os:操作系统相关操作
  • datetime:时间日期以及相关计算
  • time:处理时间、打印当前时间、强制挂起当前进程
  • requests:网络请求标准库
  • base64:进行base64编码和解码操作
  • copy:复制(深拷贝和浅拷贝)
  • configparser:读写配置文件
  • collections:提供一系列特殊的容器类

os

代码示例

Python 3.12.7 (main, Nov  8 2024, 17:55:36) [GCC 14.2.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import os
>>> os.name
'posix'
>>> filename = '/root/python_code/python_4/test/test.txt'
>>> os.path.abspath(filename)
'/root/python_code/python_4/test/test.txt'
>>> os.path.basename(filename)
'test.txt'
>>> os.path.isfile(filename)
True
>>> os.path.isdir(filename)
False
>>> dirname = '/root/python_code/python_4/test/testdir'
>>> filename2 = '/root/python_code/python_4/test/test2.txt'
>>> os.mkdir(dirname)
>>> os.rmdir(dirname)
>>> os.rename(filename,filename2)
>>>

datetime

代码示例

Python 3.12.7 (main, Nov  8 2024, 17:55:36) [GCC 14.2.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> from datetime import date,datetime
>>> date.today()
datetime.date(2025, 7, 1)
>>> datetime.now()
datetime.datetime(2025, 7, 1, 14, 32, 34, 764462)
>>> datetime.now().time()
datetime.time(14, 32, 54, 469001)
>>> print(datetime.now().time())
14:33:27.748636
>>> datetime.now().year
2025
>>> datetime.now().month
7
>>> datetime.now().day
1
>>> datetime.now().hour
14
>>> datetime.now().minute
34
>>>
>>>

time

代码示例

Python 3.12.7 (main, Nov  8 2024, 17:55:36) [GCC 14.2.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import time
>>> time.localtime()
time.struct_time(tm_year=2025, tm_mon=7, tm_mday=1, tm_hour=14, tm_min=35, tm_sec=29, tm_wday=1, tm_yday=182, tm_isdst=1)
>>> st = time.localtime()
>>> st.tm_yday
182
>>> st.tm_hour
14
>>> st.tm_mon
7
>>> time.time()
1751394967.427422
>>> def test():
...     start_time = time.time()
...     time.sleep(5.67)
...     end_time = time.time()
...     print('程序运行耗时:{:.2f}'.format(end_time - start_time))
...
>>>
>>> test()
程序运行耗时:5.68
>>>

requests

代码示例

Python 3.12.7 (main, Nov  8 2024, 17:55:36) [GCC 14.2.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import requests
>>> r = requests.get('http://www.baidu.com')
>>> r.status_code
200
>>> r.headers['content-type']
'text/html'
>>> r.text
'<!DOCTYPE html>\r\n<!--STATUS OK--><html> <head><meta http-equiv=content-type content=text/html;charset=utf-8><meta http-equiv=X-UA-Compatible content=IE=Edge><meta content=always name=referrer><link rel=stylesheet type=text/css href=http://s1.bdstatic.com/r/www/cache/bdorz/baidu.min.css><title>ç\x99¾åº¦ä¸\x80ä¸\x8bï¼\x8cä½\xa0å°±ç\x9f¥é\x81\x93</title></head> <body link=#0000cc> <div id=wrapper> <div id=head> <div class=head_wrapper> <div class=s_form> <div class=s_form_wrapper> <div id=lg> <img hidefocus=true src=//www.baidu.com/img/bd_logo1.png width=270 height=129> </div> <form id=form name=f action=//www.baidu.com/s class=fm> <input type=hidden name=bdorz_come value=1> <input type=hidden name=ie value=utf-8> <input type=hidden name=f value=8> <input type=hidden name=rsv_bp value=1> <input type=hidden name=rsv_idx value=1> <input type=hidden name=tn value=baidu><span class="bg s_ipt_wr"><input id=kw name=wd class=s_ipt value maxlength=255 autocomplete=off autofocus></span><span class="bg s_btn_wr"><input type=submit id=su value=ç\x99¾åº¦ä¸\x80ä¸\x8b class="bg s_btn"></span> </form> </div> </div> <div id=u1> <a href=http://news.baidu.com name=tj_trnews class=mnav>æ\x96°é\x97»</a> <a href=http://www.hao123.com name=tj_trhao123 class=mnav>hao123</a> <a href=http://map.baidu.com name=tj_trmap class=mnav>å\x9c°å\x9b¾</a> <a href=http://v.baidu.com name=tj_trvideo class=mnav>è§\x86é¢\x91</a> <a href=http://tieba.baidu.com name=tj_trtieba class=mnav>è´´å\x90§</a> <noscript> <a href=http://www.baidu.com/bdorz/login.gif?login&amp;tpl=mn&amp;u=http%3A%2F%2Fwww.baidu.com%2f%3fbdorz_come%3d1 name=tj_login class=lb>ç\x99»å½\x95</a> </noscript> <script>document.write(\'<a href="http://www.baidu.com/bdorz/login.gif?login&tpl=mn&u=\'+ encodeURIComponent(window.location.href+ (window.location.search === "" ? "?" : "&")+ "bdorz_come=1")+ \'" name="tj_login" class="lb">ç\x99»å½\x95</a>\');</script> <a href=//www.baidu.com/more/ name=tj_briicon class=bri style="display: block;">æ\x9b´å¤\x9a产å\x93\x81</a> </div> </div> </div> <div id=ftCon> <div id=ftConw> <p id=lh> <a href=http://home.baidu.com>å\x85³äº\x8eç\x99¾åº¦</a> <a href=http://ir.baidu.com>About Baidu</a> </p> <p id=cp>&copy;2017&nbsp;Baidu&nbsp;<a href=http://www.baidu.com/duty/>使ç\x94¨ç\x99¾åº¦å\x89\x8då¿\x85读</a>&nbsp; <a href=http://jianyi.baidu.com/ class=cp-feedback>æ\x84\x8fè§\x81å\x8f\x8dé¦\x88</a>&nbsp;京ICPè¯\x81030173å\x8f·&nbsp; <img src=//www.baidu.com/img/gs.gif> </p> </div> </div> </div> </body> </html>\r\n'
>>>
>>> r = requests.get('https://api.github.com')
>>> r.json()
{'current_user_url': 'https://api.github.com/user', 'current_user_authorizations_html_url': 'https://github.com/settings/connections/applications{/client_id}', 'authorizations_url': 'https://api.github.com/authorizations', 'code_search_url': 'https://api.github.com/search/code?q={query}{&page,per_page,sort,order}', 'commit_search_url': 'https://api.github.com/search/commits?q={query}{&page,per_page,sort,order}', 'emails_url': 'https://api.github.com/user/emails', 'emojis_url': 'https://api.github.com/emojis', 'events_url': 'https://api.github.com/events', 'feeds_url': 'https://api.github.com/feeds', 'followers_url': 'https://api.github.com/user/followers', 'following_url': 'https://api.github.com/user/following{/target}', 'gists_url': 'https://api.github.com/gists{/gist_id}', 'hub_url': 'https://api.github.com/hub', 'issue_search_url': 'https://api.github.com/search/issues?q={query}{&page,per_page,sort,order}', 'issues_url': 'https://api.github.com/issues', 'keys_url': 'https://api.github.com/user/keys', 'label_search_url': 'https://api.github.com/search/labels?q={query}&repository_id={repository_id}{&page,per_page}', 'notifications_url': 'https://api.github.com/notifications', 'organization_url': 'https://api.github.com/orgs/{org}', 'organization_repositories_url': 'https://api.github.com/orgs/{org}/repos{?type,page,per_page,sort}', 'organization_teams_url': 'https://api.github.com/orgs/{org}/teams', 'public_gists_url': 'https://api.github.com/gists/public', 'rate_limit_url': 'https://api.github.com/rate_limit', 'repository_url': 'https://api.github.com/repos/{owner}/{repo}', 'repository_search_url': 'https://api.github.com/search/repositories?q={query}{&page,per_page,sort,order}', 'current_user_repositories_url': 'https://api.github.com/user/repos{?type,page,per_page,sort}', 'starred_url': 'https://api.github.com/user/starred{/owner}{/repo}', 'starred_gists_url': 'https://api.github.com/gists/starred', 'topic_search_url': 'https://api.github.com/search/topics?q={query}{&page,per_page}', 'user_url': 'https://api.github.com/users/{user}', 'user_organizations_url': 'https://api.github.com/user/orgs', 'user_repositories_url': 'https://api.github.com/users/{user}/repos{?type,page,per_page,sort}', 'user_search_url': 'https://api.github.com/search/users?q={query}{&page,per_page,sort,order}'}
>>>

base64

代码示例

Python 3.12.7 (main, Nov  8 2024, 17:55:36) [GCC 14.2.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import base64
>>> base64.b64encode(b'hello world')
b'aGVsbG8gd29ybGQ='
>>> base64.b64decode(b'aGVsbG8gd29ybGQ=')
b'hello world'
>>>

copy

代码示例

Python 3.12.7 (main, Nov  8 2024, 17:55:36) [GCC 14.2.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> l = [1,3.14,'linux','python']
>>> l
[1, 3.14, 'linux', 'python']
>>> l2 = l
>>> l2
[1, 3.14, 'linux', 'python']
>>> l2.append('java')
>>> l2
[1, 3.14, 'linux', 'python', 'java']
>>> l
[1, 3.14, 'linux', 'python', 'java']
>>> import copy
>>> l3 = copy.copy(l)
>>> l3
[1, 3.14, 'linux', 'python', 'java']
>>> l3.append('c++')
>>> l3
[1, 3.14, 'linux', 'python', 'java', 'c++']
>>> l
[1, 3.14, 'linux', 'python', 'java']
>>> id(l3)
140345074626496
>>> id(l)
140345079581504
>>> id(l2)
140345079581504
>>>
>>> l = [1,[2,3],4]
>>> l2 = l
>>> l2[1].append(5)
>>> l2
[1, [2, 3, 5], 4]
>>> l
[1, [2, 3, 5], 4]
>>> id(l2[1])
140345073216512
>>> id(l[1])
140345073216512
>>>
>>> l3 = copy.deepcopy(l)
>>> l3
[1, [2, 3, 5], 4]
>>> l3[1].append(6)
>>> l3
[1, [2, 3, 5, 6], 4]
>>> l
[1, [2, 3, 5], 4]
>>> id(l3[1])
140345074637696
>>> id(l[1])
140345073216512
>>>

configparser

代码示例

Python 3.12.7 (main, Nov  8 2024, 17:55:36) [GCC 14.2.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> from configparser import ConfigParser
>>> config = ConfigParser()
>>> config.read('/test/a.ini',encoding='utf-8')
[]
>>> config.read('./test/a.ini',encoding='utf-8')
['./test/a.ini']
>>> config.sections()
['user', 'courses']
>>> config.options('user')
['name', 'id', 'date']
>>> config.items('user')
[('name', "'burgess'"), ('id', '2000'), ('date', '2015.7.1')]
>>> config.get('user','name')
"'burgess'"
>>>
>>> config.add_section('permission')
>>> config.set('permission','allow','True')
>>> with open('./test/a.ini','w',encoding='utf-8') as f:
...     config.write(f)
...
>>>

collections

代码示例

Python 3.12.7 (main, Nov  8 2024, 17:55:36) [GCC 14.2.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> from collections.abc import Iterator
>>> isinstance('hello',Iterator)
False
>>> isinstance(iter('hello'),Iterator)
True
>>> from collections.abc import Generator
>>> isinstance(iter('hello'),Generator)
False
>>> g = (i ** 2 for i in range(10))
>>> g
<generator object <genexpr> at 0x7f2ad21eacf0>
>>> isinstance(g,Generator)
True
>>> from collections.abc import Iterable
>>> isinstance('hello',Iterable)
True
>>>
>>> from collections import OrderedDict
>>> d = OrderedDict()
>>> d['alibaba'] = 1
>>> d['google'] = 2
>>> d['ms'] = 3
>>> for key in d:
...     print(key,d[key])
...
alibaba 1
google 2
ms 3
>>>
>>> import json
>>> json.dumps(d)
'{"alibaba": 1, "google": 2, "ms": 3}'
>>>
>>> from collections import namedtuple
>>> Point = namedtuple('Point',['x','y'])
>>> p = Point(2,3)
>>> p.x
2
>>> p.y
3
>>>
>>> from collections import Counter
>>> c = Counter('https://www.baidu.com')
>>> c
Counter({'w': 3, 't': 2, '/': 2, '.': 2, 'h': 1, 'p': 1, 's': 1, ':': 1, 'b': 1, 'a': 1, 'i': 1, 'd': 1, 'u': 1, 'c': 1, 'o': 1, 'm': 1})
>>> c.most_common(3)
[('w', 3), ('t', 2), ('/', 2)]
>>>
posted on 2025-07-02 20:48  burgess0x  阅读(8)  评论(0)    收藏  举报