面試題:python
定義模塊時能夠把一個py文件或一個文件夾(包)看成一個模塊,以方便於之後其餘py文件的調用 。web
對於包(文件夾)的定義:面試
py2:文件見中必須有 _ init _.py 。手工建立此文件便可。json
在pycharm中手工建立python package時候,默認自動會在這個文件中建立--init--.py文件。app
py3:不須要 _ init _.py .dom
推薦你們之後寫代碼時,都要加上此文件。socket
# lizhongwei.py #!/usr/bin/env python # -*- coding:utf-8 -*- def show(): print('我司裏種種') def func(): pass print(456)
# 導入模塊,加載此模塊中全部的值到內存。因此此時先打印出:456。後打印該代碼塊下面的123。 import lizhongwei print(123) # 調用模塊中的函數 lizhongwei.func()
# 導入模塊 from lizhongwei import func,show from lizhongwei import func from lizhongwei import show from lizhongwei import * func()#from導入方法,直接使用函數。
# 導入模塊 from lizhongwei import func as f#別名法,防止func函數與現有代碼中函數重名。 def func(): print(123) f()
導入模塊:函數
lizhong - jd.py - pdd.py - tb.py 包.py
#上個代碼框中的文件夾中文件,引用以下方法: import lizhong.jd lizhong.jd.f1()
from lizhong import jd jd.f1()
from lizhong.jd import f1 f1()
注意: sys.path的做用是什麼?sys.path默認在py的安裝目錄和執行文件當前所在的目錄。ui
一、若是要增長非py安裝目錄下,須要append非py安裝目錄。sys.path.append('path')。google
而後在引用目錄下的py文件就能夠引用成功:如:import page
二、若是page的上級目錄和執行的文件在同一個目錄(lib),這樣引用也能夠:
from lib import page
三、若是page和執行的py文件在同一個目錄下,直接引用便可。
import page
將父級目錄加入sys.path中,方便後期調用此父級下的代碼塊。 import sys v=sys.path print(v) import os print(__file__) print(os.path.dirname(__file__)) print(os.path.abspath(__file__)) print(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) DIR=os.path.dirname(os.path.dirname(os.path.abspath(__file__))) sys.path.append(DIR) print(sys.path) === ['C:\\python\\venv', 'C:\\python', 'C:\\python\\python36\\python36.zip', 'C:\\python\\python36\\DLLs', 'C:\\python\\python36\\lib', 'C:\\python\\python36', 'C:\\python\\python36\\lib\\site-packages', 'C:\\python\\PyCharm 2019.2.2\\PyCharm 2018.2.1\\helpers\\pycharm_matplotlib_backend'] C:/python/venv/day15.py C:/python/venv C:\python\venv\day15.py C:\python ['C:\\python\\venv', 'C:\\python', 'C:\\python\\python36\\python36.zip', 'C:\\python\\python36\\DLLs', 'C:\\python\\python36\\lib', 'C:\\python\\python36', 'C:\\python\\python36\\lib\\site-packages', 'C:\\python\\PyCharm 2019.2.2\\PyCharm 2018.2.1\\helpers\\pycharm_matplotlib_backend', 'C:\\python']
os
sys
time
json
dumps
loads
注意:
字典或列表中若有中文,序列化時想要保留中文顯示:
v = {'k1':'alex','k2':'李傑'} import json val = json.dumps(v,ensure_ascii=False)#保留中文 print(val)
dump
import json v = {'k1':'alex','k2':'李傑'} f = open('x.txt',mode='w',encoding='utf-8') val = json.dump(v,f) print(val) f.close()
load
import json v = {'k1':'alex','k2':'李傑'} f = open('x.txt',mode='r',encoding='utf-8') data = json.load(f) f.close() print(data,type(data))
haslib
random
getpass
shutil
copy
import pickle # #################### dumps/loads ###################### """ v = {1,2,3,4} val = pickle.dumps(v)#序列化出來不可讀 print(val) data = pickle.loads(val) print(data,type(data)) """ """ #序列化函數(json作不到): def f1(): print('f1') v1 = pickle.dumps(f1) print(v1) v2 = pickle.loads(v1) v2() """ # #################### dump/load ###################### # v = {1,2,3,4} # f = open('x.txt',mode='wb') # val = pickle.dump(v,f) # f.close() # f = open('x.txt',mode='rb') # data = pickle.load(f) # f.close() # print(data) ================== encording後稱做字節 json:得出來的是字符串 pickle:得出來的是字符串
import shutil # 刪除目錄 # shutil.rmtree('test') # 重命名,文件和目錄均可以 # shutil.move('test','ttt') # 壓縮文件 # shutil.make_archive('zzh','zip','D:\code\s21day16\lizhong') # 解壓文件,有目錄直接解壓,無目錄,則直接建立 # shutil.unpack_archive('zzh.zip',extract_dir=r'D:\code\xxxxxx\xxxx',format='zip')
示例
import os import shutil from datetime import datetime ctime = datetime.now().strftime('%Y-%m-%d-%H-%M-%S') # 1.壓縮lizhongwei文件夾 zip # 2.放到到 code 目錄(默認不存在) # 3.將文件解壓到D:\x1目錄中。 if not os.path.exists('code'): os.makedirs('code') shutil.make_archive(os.path.join('code',ctime),'zip','D:\code\s21day16\lizhongwei') file_path = os.path.join('code',ctime) + '.zip' shutil.unpack_archive(file_path,r'D:\x1','zip')
UTC/GMT:世界時間
本地時間:本地時區的時間。
# https://login.wx.qq.com/cgi-bin/mmwebwx-bin/login?loginicon=true&uuid=4ZwIFHM6iw==&tip=1&r=-781028520&_=1555559189206
#!/usr/bin/env python # -*- coding:utf-8 -*- import time from datetime import datetime,timezone,timedelta # ######################## 獲取datetime格式時間 ############################## """ v1 = datetime.now() # 當前本地時間 print(v1) tz = timezone(timedelta(hours=7)) # 當前東7區時間 v2 = datetime.now(tz) print(v2) v3 = datetime.utcnow() # 當前UTC時間 print(v3) """ print(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')) # ######################## 把datetime格式轉換成字符串 ############################## # v1 = datetime.now() # print(v1,type(v1)) # val = v1.strftime("%Y-%m-%d %H:%M:%S") # print(val) # ######################## 字符串轉成datetime ############################## # v1 = datetime.strptime('2011-11-11','%Y-%m-%d') # print(v1,type(v1)) # ######################## datetime時間的加減 ############################## # v1 = datetime.strptime('2011-11-11','%Y-%m-%d') # v2 = v1 - timedelta(days=140) # date = v2.strftime('%Y-%m-%d') # print(date) # ######################## 時間戳和datetime關係 ############################## # ctime = time.time() # print(ctime) # v1 = datetime.fromtimestamp(ctime) # print(v1) # v1 = datetime.now() # val = v1.timestamp() # print(val)
try: val = input('請輸入數字:') num = int(val) except Exception as e: print('操做異常')
# import requests # # try: # ret = requests.get('http://www.google.com') # print(ret.text) # except Exception as e: # print('請求異常')
def func(a): try: return a.strip() except Exception as e: pass return False v = func('alex') if not v: print('函數執行失敗') else: print('結果是',v)
練習題
# 1. 寫函數,函數接受一個列表,請將列表中的元素每一個都 +100 def func(arg): result = [] for item in arg: if item.isdecimal(): result.append(int(item) + 100) return result # 2. 寫函數去,接受一個列表。列表中都是url,請訪問每一個地址並獲取結果。 import requests def func(url_list): result = [] try: for url in url_list: response = requests.get(url) result.append(response.text) except Exception as e: pass return result def func2(url_list): result = [] for url in url_list: try: response = requests.get(url) result.append(response.text) except Exception as e: pass return result func(['http://www.baidu.com','http://www.google.com','http://www.bing.com']) 異常處理結構: try: pass except Exception as e: pass