zoukankan      html  css  js  c++  java
  • 常用python代码

    1)调用系统命令

    调用SHELL命令nslookup,将执行的结果保存到变量result_nslook中

    import os
    
    cmd='nslookup %s' % hostname
    handle=os.popen(cmd , 'r')
    result_nslook=handle.read()
     

    调用shell命令但是不需要获取返回结果

    import os
    
    cmd='ls'
    os.system(cmd)
    

    2)Python 的字符串处理

    去掉前后空格

    input = open('hostlist_ip' , 'r')
    
    for hostname in input.xreadlines():
    
    #按行读文件到hostname中
        hostname=hostname.strip()
        hostlist.append(hostname)
    input.close()
    

    将读入的一个字符串数组按照空格划分为list

    temp=display.split()
    for seg in temp:
        if seg[0:5]=='time=':
                output.write(seg.lstrip('time=').strip()+'\t')
                delayRec.append(seg.lstrip('time='))
    
    

    3)文件操作

    打开文件进行读写

    import os
    
    input=open(filename ,'r')  #读文件
    output=open(filename ,'w') #写文件
    output=open(filename,'a')  #追加写文件
    
    

    遍历文件夹操作

    import os
    
    for root, dirs, files in os.walk(path, topdown=False):
    #hanlde file
    for name in files:
    if name[:-3] = 'exe':
    print name
    
    

    #删除文件

    top='mydata/'
    for root,dir,files in os.walk(top,topdown=False):
          for name in files: 
         os.remove(os.path.join(root,name))
    
    os.rmdir('mydata')
    os.mkdir('mydata')
    
    

    列出文件

    import os
    
    os.listdir("c:\\music\\_singles\\") 
    
    ['a_time_long_forgotten_con.mp3', 'hellraiser.mp3', 'kairo.mp3',
    'long_way_home1.mp3', 'sidewinder.mp3', 'spinning.mp3']
     
    

    4)如果将Blob存储到SQLite中

    有时候我们需要将Blob或者二进制文件对象存储到SQLite数据库中,下面这个例子演示了,Python中是如何实现的:

    import os
    import sqlite
    
    class Blob:
        """Automatically encode a binary string."""
        def __init__(self, s):
            self.s = s
    
        def _quote(self):
            return "'%s'" % sqlite.encode(self.s)
    
    db = sqlite.connect("test.db")
    cursor = db.cursor()
    cursor.execute("CREATE TABLE t (b BLOB);")
    s = "\0"*50 + "'"*50
    cursor.execute("INSERT INTO t VALUES(%s);", Blob(s))
    cursor.execute("SELECT b FROM t;")
    b = cursor.fetchone()[0]
    assert b == s # b is automatically decoded
    db.close()
    os.remove("test.db")
    
    
  • 相关阅读:
    Tensorflow项目中--FLAGS=tf.flags.FLAGS
    霍夫变换--直线,圆的识别
    利用手写数字识别项目详细描述BP深度神经网络的权重学习
    安装Tensorflow
    安装Anaconda
    关于hibernate查询映射时无法反序列化问题
    postgresql安装之后修改默认用户密码
    中文乱码之springboot框架中两工程之间参数传递乱码
    springboot注解小记1
    springboot开发笔记
  • 原文地址:https://www.cnblogs.com/xupeizhi/p/2908882.html
Copyright © 2011-2022 走看看