zoukankan      html  css  js  c++  java
  • 【Tip】Python

    『基本操作』

    【查看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+'
    ')    
    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
  • 相关阅读:
    论登陆博客园的时候忘记了密码
    LNOI 2019 旁观记
    [bzoj3790] 神奇项链
    [POI2000] 病毒
    [HAOI2008] 移动玩具
    [codevs1288] 埃及分数
    [hdu1401] Solitaire
    [洛谷P3806] [模板] 点分治1
    [国家集训队] 聪聪可可
    [洛谷P4178] Tree
  • 原文地址:https://www.cnblogs.com/glife/p/tip-py.html
Copyright © 2011-2022 走看看