1. 程式人生 > >Python入門17

Python入門17

os模組的補充

import os
import time
time1=os.path.getctime('/etc/group')
tuple_time=time.localtime(time1)
year=tuple_time.tm_year
month=tuple_time.tm_mon
day=tuple_time.tm_mday
with open('data.txt','w')as f:
    f.write('%d %d %d' %(year,month,day))
##常用時間轉換
#1.把元組的時間轉換為時間戳
tuple_time=time.localtime()
print
(time.mktime(tuple_time)) #2.把元組時間轉換為字串格式 print(time.strftime('%Y-%m-%d')) print(time.strftime('%T')) print(time.strftime('%F')) #3.把字串格式轉換為元組 s='2018-10-1' print(time.strptime(s,'%Y-%m-%d')) s_time='12:20:30' print(time.strptime(s_time,'%H:%M:%S'))

這裡寫圖片描述

datetime模組詳解

from datetime import date
from datetime import
time from datetime import datetime from datetime import timedelta #獲取當前的日期 print(date.today()) #物件加或者減一個時間間隔,返回一個新的日期物件 d=date.today() print(d) delta=timedelta(days=3) print(d-delta) d=datetime.now() print(d)

這裡寫圖片描述

namedtupled新型資料型別

from collections import namedtuple

User=namedtuple('User',['name'
,'age','gender']) u=User('lijia',20,'female') print(u.name) print(u)

這裡寫圖片描述

json模組

import json
#將python物件編碼成為json的字串格式;
d={'name':'lijia'}
jsonStr=json.dumps(d)
print(jsonStr,type(jsonStr))
l=[1,2,3,4]
jsonli=json.dumps(l)
print(jsonli,type(jsonli))
# 將獲取的json字串解碼為python的物件
pythonDict=json.loads(jsonStr)
print(pythonDict,type(pythonDict))

# 將python物件編碼成為json的字串格式並寫入檔案中;
with open('json.txt','w')as f:
    json.dump(d,f)
#將檔案中的json字串解碼為python的物件
with open('json.txt')as f:
    json_Dict=json.load(f)
    print(json_Dict,type(json_Dict))

import json
import string
from random import choice

keys = string.ascii_lowercase
values = string.ascii_letters + string.digits

dict = {choice(keys): choice(values) for i in range(100)}
with open('json.txt', 'w') as f:
    # separators = ("每個元素間的分隔符", “key和value之間的分隔符”)
    json.dump(dict, f, indent=4, sort_keys=True, separators=(';', '='))

這裡寫圖片描述

應用案例之系統監控

#獲取當前主機資訊,包含作業系統名,主機名,核心版本,硬體架構等
import datetime
import os

import time
from datetime import datetime
from psutil._common import suser

info=os.uname()
print('1.主機資訊'.center(50,'*'))
print("""
    作業系統:%s,
    主機名:%s,
    核心版本:%s,
    硬體架構:%s,
""" %(info.sysname,info.nodename,info.release,info.machine))
#獲取開機時間和開機時長
print('2.開機時間'.center(50,'*'))
#獲取開機時間的時間戳,需要安裝psutil模組
import psutil
boot_time=psutil.boot_time()
#將時間戳轉換為字串格式,2種方法,任選一種
# print(time.ctime(boot_time))
boot_time=datetime.fromtimestamp(boot_time)
#獲取當前時間
now_time=datetime.now()
#獲取時間差
delta_time=now_time-boot_time
delta_time=str(delta_time).split('.')[0]
now_time=str(now_time).split('.')[0]
print("""
    開機時間:%s
    當前時間:%s
    開機時長:%s
""" %(boot_time,now_time,delta_time))
#獲取當前登陸使用者
print('3.當前登陸使用者'.center(50,'*'))
#獲取當前登陸使用者的詳細資訊,需求是獲取使用者名稱和登陸主機
users=psutil.users()
#獲取需要的資訊
users={'%s %s' %(user.name,user.host) for user in users}
#實現資訊的去重
for user in users:
    print('\t %s' %(user))

print(psutil.disk_partitions())
print(psutil.version_info)
print(psutil.virtual_memory())

這裡寫圖片描述

獲取ip對應的地理位置

import json
from urllib.request import urlopen
ip=input('請輸入查詢的ip:')
url="http://ip.taobao.com/service/getIpInfo.php?ip=%s" %(ip)
# 根據url獲取網頁的內容, 並且解碼為utf-8格式, 識別中文;
text= urlopen(url).read().decode('utf-8')
print(text)
print(type(text))
# 將獲取的字串型別轉換為字典, 方便處理
d = json.loads(text)['data']
country = d['country']
city = d['city']
print(country, city)

這裡寫圖片描述

python和excel的操作

excel文件的基本定義
- 工作薄(workbook)
- 工作表(sheet)
- 活動表(active sheet)
- 行(row): 1,2,3,4,5,6........
- 列(column): A,B,C,D........
- 單元格(cell): B1, C1
"""
import openpyxl
#1.開啟一個excel文件,class 'openpyxl.workook'例項化出來的物件
wb=openpyxl.load_workbook('example.xlsx')
#獲取當前工作簿裡所有的工作表和正在使用的表
print(wb.sheetnames)
print(wb.active)
#2.選擇要操作的工作表,返回工作表物件
sheet=wb['Sheet1']
#獲取工作表名稱
print(sheet.title)
#3.返回指定行指定列的單元格資訊
print(sheet.cell(row=1,column=2).value)
cell=sheet['B1']
print(cell)
print(cell.row,cell.column,cell.value)
#4.獲取工作表中行和列的最大值
print(sheet.max_column)
print(sheet.max_row)
sheet.title='學生資訊'
print(sheet.title)
#5.訪問單元格的所有資訊
print(sheet.rows)
#迴圈遍歷每一行
for row in sheet.rows:
    #迴圈遍歷每一個單元格
    for cell in row:
        #獲取單元格內容
        print(cell.value)
    print()
#6.儲存修改資訊
wb.save(filename='example.xlsx')

操作Excel表格可詳細的概括如下:
1.匯入 openpyxl 模組。
2.呼叫 openpyxl.load_workbook()函式。
3.取得 Workbook 物件。
4.呼叫 wb.sheetnames和 wb.active 獲取工作簿詳細資訊。
5.取得 Worksheet 物件。
6.使用索引或工作表的 cell()方法,帶上 row 和 column 關鍵字引數。
7.取得 Cell 物件。
8.讀取 Cell 物件的 value 屬性

Excel簡單例項

  • 定義一個函式, readwb(wbname, sheetname=None)
  • 如果使用者指定sheetname就開啟使用者指定的工作表, 如果沒有指定, 開啟active sheet;
  • 根據商品的價格進行排序(由小到大), 儲存到檔案中;商品名稱:商品價格:商品數量
  • 所有資訊, 並將其儲存到資料庫中
import os
import openpyxl

def readwb(wbname, sheetname=None):
    # 開啟工作薄
    wb = openpyxl.load_workbook(wbname)
    # 獲取要操作的工作表
    if not sheetname:
        sheet = wb.active
    else:
        sheet = wb[sheetname]

    # 獲取商品資訊儲存到列表中
    #[ ['name', price, count]
    all_info = []
    for row in sheet.rows:
        child = [cell.value for cell in row]
        all_info.append(child)
    return sorted(all_info, key=lambda item: item[1])

def save_to_excel(data, wbname, sheetname='sheet1'):
    """
    將資訊儲存到excel表中;
    [[' BOOK', 50, 3], ['APPLE', 100, 1], ['BANANA', 200, 0.5]]
    """
    print("寫入Excel[%s]中......." %(wbname))
    # 開啟excel表, 如果檔案不存在, 自己例項化一個WorkBook物件
    wb = openpyxl.Workbook()
    # 修改當前工作表的名稱
    sheet = wb.active
    # 修改工作表的名稱
    sheet.title = sheetname

    for row, item in enumerate(data):  # 0 [' BOOK', 50, 3]
        for column, cellValue in enumerate(item): #  0 ' BOOK'
            sheet.cell(row=row+1, column=column+1, value=cellValue)

    # ** 往單元格寫入內容
    # sheet.cell['B1'].value = "value"
    # sheet.cell(row=1, column=2, value="value")

    # 儲存寫入的資訊
    wb.save(filename=wbname)
    print("寫入成功!")

data = readwb(wbname='Book1.xlsx')
save_to_excel(data, wbname='Book2.xlsx', sheetname="排序商品資訊")

這裡寫圖片描述