python小技巧——实时更新

  1. 获取所有目录及文件

    for root, dirs, files in os.walk(os.getcwd()):  
        print(root) #当前目录路径  
        print(dirs) #当前路径下所有子目录  
        print(files) #当前路径下所有非目录子文件 
  2. 创建文件夹

    isExists=os.path.exists(path)
    if not isExists:
        os.makedirs(path) 
    else:
        print path+'目录已存在'
  3. 获取当前路径下所有目录及文件

    import glob    
    glob.glob('C:\\snow\\*.*')  #获取目录[C:\\snow\\]下面所有的文件
    glob.glob('C:\\snow\\*.*')  #获取目录[C:\\snow\\]下面所有.txt文件
  4. 数据库连接

    import os, sys
    import pymysql
    class mySql(object):
        def __init__(self):
            self.Conn=None
            self.Cursor=None
    
        def conn(self):
            try:
                self.Conn = pymysql.connect(host='localhost',user='root',passwd='19940512',db='snow')
                self.Cursor = self.Conn.cursor()
            except Exception as e:
                print (e)
    
        def closeconn(self):
            if self.Conn:
                if self.Cursor:
                    self.Cursor.close()
                self.Conn.close()
    
        def getDotInfo(self,table, num, offset,):
            rows=0;
            try:
                self.conn()
                sql='select T_Longitude,T_Latitude,T_Speed,T_Heading,T_TargetID,T_UTCTime from %s limit %r offset %r' % (table, num, offset)
                #print(sql) 
                n = self.Cursor.execute(sql)
                rows = self.Cursor.fetchall()
            except Exception as e:
                pass
            self.closeconn()
            return rows
  5. python2与python3兼容方法

    https://www.zhihu.com/question/21653286
    https://zhuanlan.zhihu.com/p/21261875
    https://www.cnblogs.com/zanjiahaoge666/p/7413419.html

  6. 常用的模块
    numpy,matplotlib,pandas,scipy —— 数据挖掘与分析的基础
    scikit-learn —— 数据挖掘与分析

  7. 字典key与value互换

    >>> a_dict = {'a': 1, 'b': 2, 'c': 3}
    >>> {value:key for key, value in a_dict.items()}
    {1: 'a', 2: 'b', 3: 'c'}
  8. 字典赋值

    dict = {‘’a': 1, 'b':1}
    dict['c'] = dict.get('c',0) + 1
    >>>dict
    { 'a':1 ,  'b': 1,  'c':1}
  9. 采样(LDA用到了)
    [numpy]random.choice()随机选取内容
    https://blog.csdn.net/autoliuweijie/article/details/51982514

你可能感兴趣的:(python)