天天看點

【Tip】Python『基本操作』『檔案/檔案夾/IO操作』『資料操作』『常用方法』

『基本操作』

【檢視Python所在目錄】

import os
print(os.__file__)
           

【檢視已安裝的包】

pip list
           

  

【擷取目前腳本所在目錄】

import sys
import os
print(sys.argv[0])	#目前腳本所在目錄
print(sys.path[0])	#目前腳本所在目錄
print(os.path.split(os.path.realpath(__file__))[0])	#目前腳本所在目錄
print(__file__)	#目前腳本所在 路徑

curr_path = sys.path[0]
if not os.path.isdir(curr_path):curr_path = curr_path[0:curr_path.rfind('\\')]
           

【檢查變量是否存在】  

return ('VAR_NAME' in dir())
           

〖日期時間〗

【日期時間操作】

import datetime, time

#【擷取時間戳】
timestamp = int(time.mktime(time.localtime()))

#【格式化目前時間】
dtime = datetime.datetime.now()
print(dtime.strftime('%Y-%m-%d %H:%M:%S')) #年-月-日 時:分:秒
print(dt.isoweekday()) #星期(1-7:一~日)

#【字元串轉時間】
t=time.strptime('2017-11-22 12:34:56','%Y-%m-%d %H:%M:%S')
y,m,d,h,min,s=t[0:6] #儲存時間各部分變量
dtime = datetime.datetime(y,m,d,h,min,s)
print(dtime)

#【日期加減】
#    獲得今天的日期
today = datetime.date.today()
yesterday = today - datetime.timedelta(days=1) #昨天
tomorrow = today + datetime.timedelta(days=1) #明天
           

  

【睡眠n秒】

import time

time.sleep(3)  #睡眠3秒
           

〖字元串〗

【左邊自動補零】

#way-1: 生成分秒為[1,59]随機數的時間字元串,當分秒<10時左邊自動補零
tstr='2018-01-22 09:{:0>2d}:{:0>2d}'.format(int(random.uniform(1,59)),int(random.uniform(1,59))) 

#way-2:000123
print(str(123).zfill(6))
           

  

『檔案/檔案夾/IO操作』

【讀取檔案】

open('c:\\xxx', 'r', encoding='utf-8').read()
           

【周遊檔案夾】

1 import sys
2 import os
3 #周遊列舉腳本所在目錄下所有檔案
4 for parent,dirnames,filenames in os.walk(sys.path[0]):
5     for fn in filenames:
6         print(fn)
7     break # stop iterate dirs      
1 import os
2 import os.path
3 res = ''
4 #三個參數:分别傳回1.父目錄 2.所有檔案夾名字(不含路徑) 3.所有檔案名字
5 for parent,dirnames,filenames in os.walk('G:\hylt'):
6   for fn in filenames:
7     res += (fn+'\r\n')    
8 #print(res)      

View Code

【儲存檔案】

sv = open('temp_file.txt', 'w') 
sv.write(res) 
sv.close() 
print('END')
           

  

『資料操作』

【對象—> json字元串(dumps)】

import json

data = {
    'name' : 'ACME',
    'shares' : 100,
    'price' : 542.23
}
# 對象轉json
json_str = json.dumps(data)


# --json儲存到檔案
with open('data1.json', 'w') as f:
    json.dump(data, f)
           

【json字元串—>對象(loads)】

import json

# json轉對象
jobj = json.loads('{"f1":"aaa","f2":345}')

# --從檔案讀取json(為對象)
with open('data1.json', 'r') as f:
    jobj = json.load(f)
           

【string、對象互轉】

# 把一個對象轉換為字元串,類似java的toString()
_str = repr(object)

# 把repr() 轉換的字元串 變為對象 
_obj = eval(_str)
           

【 清單操作】

ref

『Pandas操作』

-

『常用方法』

【網絡下載下傳】

1 from urllib import request
 2 
 3 #----------------------------------------------------------------------
 4 def get_data(url, encoding='utf-8'):
 5     """擷取網絡資源"""
 6     i_headers = {
 7         'User-Agent': r'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) '
 8                       r'Chrome/45.0.2454.85 Safari/537.36 115Browser/6.0.3',
 9         'Connection': 'keep-alive'
10     }
11     req = request.Request(url, headers=i_headers)
12     uri = request.urlopen(req)
13     html = ''
14     if url == uri.geturl():
15         html = uri.read()
16         html = html.decode(encoding)
17     return html      

轉載于:https://www.cnblogs.com/glife/p/tip-py.html

上一篇: Python Tip