1. 程式人生 > 其它 >os模組、sys模組、json模組、process模組

os模組、sys模組、json模組、process模組

本章內容

  • os模組
  • sys模組
  • json模組
  • subprocess模組

os模組

import os
import sys

# print(sys.path)
"""建立檔案目錄"""
# os.mkdir(r'aaa')
# os.mkdir(r'bb\cc')
# os.makedirs(r'ccc')
# os.makedirs(r'bb\cc\dd')

"""刪除目錄"""
# os.rmdir(r'ccc')
# os.removedirs(r'bb') # OSError: [WinError 145] 目錄不是空的。: 'bb'
# 使用removedirs方法如果外層目錄也是空的則繼續刪除
# os.removedirs(r'F:\python_work\day 21\bb\cc\dd')

"""3.檢視某個路徑下"""
# print(os.listdir()) # ['.idea', 'aaa', 'bb', 'ccc', 'os 模組.py']
# print(os.listdir(r'bb\cc'))  # ['dd']

"""4.刪除檔案、重新命名檔案"""
# remove不能刪除資料夾,只能刪除檔案,eg:
# os.remove(r'aaa')  # PermissionError: [WinError 5] 拒絕訪問。: 'aaa'
# os.remove(r'abc.txt')
# os.rename(r'abc.txt',r'aaa.txt')

"""5.獲取當前路徑"""
# print(os.getcwd())  # F:\python_work\day 21
# os.chdir(r'C:')   # 切換路徑
# print(os.getcwd())  # C:\

"""6.軟體開發目錄規範 啟動指令碼相容性操作"""
# 6.1 動態獲取當前執行檔案所在的絕對路徑
# print(os.path.dirname(__file__))  # F:/python_work/day 21
# 6.2 每巢狀一層就是往上切換一層目錄的絕對路徑
# print(os.path.dirname(os.path.dirname(__file__)))  # F:/python_work
# 6.3 動態獲取當前執行檔案自身的路徑
# print(os.path.abspath(__file__))  # F:\python_work\day 21\os 模組.py

"""7.判斷當前路徑下的某個檔案是否存在"""
# 獲取當前路徑
# print(sys.path)  # 預設第一個路徑 F:\\python_work\\day 21
# print(os.path.exists(r'aaa'))  # True
# print(os.path.exists(r'os 模組.py'))  # True
# 判斷路徑是否是一個資料夾
# print(os.path.isdir(r'os 模組.py'))  # False
# print(os.path.isdir(r'aaa'))  # True

"""8.拼接路徑"""
# base_path = 'bb'
# ex_path = '路徑拼接'
# print(base_path + '/' + ex_path)  # 手動拼接 bb/路徑拼接
# join方法進行拼接,自動識別系統的分隔符
# res = os.path.join(base_path,ex_path)
# print(res)  # # bb\路徑拼接

"""9.獲取檔案大小  單位是位元組(bytes)"""
# print(os.path.getsize(r'bb'))  # 0
# print(os.path.getsize(r'os 模組.py'))  # 2151

"""10.瀏覽路徑下的檔案內容(文字)"""
# # 1.先獲取目標檔案路徑(動態獲取 也可以省事先寫死)
# target_path = os.path.dirname(__file__)
# full_path = os.path.join(target_path, 'ccc')
# # 2.列舉該路徑下所有的檔名稱
# file_name_list = os.listdir(full_path)  # ['a.txt', 'b.txt', 'c.txt']
# while True:
#     # 3.迴圈展示每個檔名稱
#     for i, j in enumerate(file_name_list, start=1):
#         print(i, j)
#     # 4.獲取使用者選擇的編號
#     target_num = input('請輸入您想要檢視的檔案編號>>>:').strip()
#     # 5.判斷是否是純數字
#     if target_num.isdigit():
#         # 6.如果是純數字 轉換成整型
#         target_num = int(target_num)
#         # 7.判斷數字在不在數量範圍內
#         if target_num in range(1, len(file_name_list) + 1):
#             # 8.獲取檔名稱
#             file_name = file_name_list[target_num - 1]
#             # 9.拼接完整路徑
#             full_file_path = os.path.join(full_path, file_name)
#             # 10.檔案操作開啟檔案
#             with open(full_file_path, 'r', encoding='utf8') as f:
#                 print(f.read())
#         else:
#             print('沒有該編號的檔案')
#     else:
#         print('編號只能是數字')
"""如果是其他型別的檔案 那麼普通的檔案操作是沒有正常開啟並觀看的"""

sys模組

"""該模組主要是跟python直譯器打交道"""

import sys
# # 1.列舉當前執行檔案所在的sys.path
# print(sys.path)  # ['F:\\python_work\\day 21',...]
# # 2.獲取直譯器版本資訊
# print(sys.version)  # 3.6.8 (tags/v3.6.8:3c6b436a57,...)
# # 3.獲取平臺資訊
# print(sys.platform)  # win32
# # 4.自定義命令列操作
# print(sys.argv)  # ['F:/python_work/day 21/sys 模組.py']
"""模擬cmd命令"""

# if len(sys.argv) == 3:  # 這裡的 3 表示的是命令列中可輸入三個元素
# 本身檔案路徑佔一個位置
# 這裡的判斷也可以變成異常捕獲的形式
#     username = sys.argv[1]
#     password = sys.argv[2]
#     if username == 'tony' and password == '123':
#         print('可以正常執行該檔案')
#     else:
#         print('使用者名稱或密碼錯誤 沒有該檔案的執行許可權')
# else:
#     print('請輸入使用者名稱和密碼 不能漏寫或多寫')

"""
在terminal 中輸入:python3 "sys 模組.py" tony 123
執行後會列印  '可以正常執行該檔案'
"""

"""異常捕獲的形式"""
# try:
#     username = sys.argv[1]
#     password = sys.argv[2]
# except Exception:
#     print('請輸入使用者名稱和密碼')
# else:
#     if username == 'tony' and password == '123':
#         print('可以正常執行該檔案')
#     else:
#         print('使用者名稱或密碼錯誤 沒有該檔案的執行許可權')

json模組

"""
json.dumps()        序列化
    將python資料型別轉換成json格式字串
json.loads()        反序列化
    將json格式字串轉換成對應的資料型別
"""
import json

"""1.dumps   序列化"""
# d = {'name': 'tony', 'age': 18}
# d = str(d)
# print(d,type(d))  # {'name': 'tony', 'age': 18} <class 'str'>
# res = d.encode('utf8')
# print(res,type(res))  # b"{'name': 'tony', 'age': 18}" <class 'bytes'>
# # 轉換成json格式的字串 ""  ""
# new_d = json.dumps(d)
# print(new_d,type(new_d))  # "{'name': 'tony', 'age': 18}" <class 'str'>
# 編碼
# en_d = new_d.encode('utf8')  # 此時變成bytes型別
# print(en_d, type(en_d))  # b'{"name": "tony", "age": 18}' <class 'bytes'>
"""2.loads  反序列化"""
# 解碼
# de_d = en_d.decode('utf8')
# 此時變成json格式字串
# print(de_d, type(de_d))  # {"name": "tony", "age": 18} <class 'str'>
# 轉換成原本格式
# dict_d = json.loads(de_d)
# print(dict_d, type(dict_d))  # {'name': 'tony', 'age': 18} <class 'dict'>

"""可支援序列化和反序列化的資料型別如下:"""

"""
    +-------------------+---------------+
    | Python            | JSON          |
    +===================+===============+
    | dict              | object        |
    +-------------------+---------------+
    | list, tuple       | array         |
    +-------------------+---------------+
    | str               | string        |
    +-------------------+---------------+
    | int, float        | number        |
    +-------------------+---------------+
    | True              | true          |
    +-------------------+---------------+
    | False             | false         |
    +-------------------+---------------+
    | None              | null          |
    +-------------------+---------------+
"""

subprocess模組

import subprocess
# ls在終端的意思就是檢視當前路徑下所有的檔名稱
res = subprocess.Popen('dir',
                       shell=True,
                       stdout=subprocess.PIPE,
                       stderr=subprocess.PIPE
                       )
print('stdout',res.stdout.read().decode('utf8','ignore'))  # 獲取正確命令執行之後的結果
print('stderr',res.stderr.read().decode('utf8','ignore'))  # 獲取錯誤命令執行之後的結果
"""
該模組可以實現遠端操作其他計算機的功能
    動態獲取命令執行並返回結果
        eg:類似於Xshell軟體的功能
"""