专栏中心

EEPW首页 > 专栏 > Python开发常用的代码有哪些

Python开发常用的代码有哪些

发布人:扣丁学堂 时间:2020-07-14 来源:工程师 发布文章

  在Python学习中,时常会遇到各种不同难度的代码,为了方便大家学习,扣丁学堂为大家专门总结了一下在学习Python编程时将会遇到的常用代码,以便对大家的学习能有所帮助。

5.png

  1)调用系统命令


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


  importos


  cmd='nslookup%s'%hostname


  handle=os.popen(cmd,'r')


  result_nslook=handle.read()


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


  importos


  cmd='ls'


  os.system(cmd)


  2)Python的字符串处理


  去掉前后空格


  input=open('hostlist_ip','r')


  forhostnameininput.xreadlines():


  #按行读文件到hostname中


  hostname=hostname.strip()


  hostlist.append(hostname)


  input.close()


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


  temp=display.split()


  forsegintemp:


  ifseg[0:5]=='time=':


  output.write(seg.lstrip('time=').strip()+'\t')


  delayRec.append(seg.lstrip('time='))


  3)文件操作


  打开文件进行读写


  importos


  input=open(filename,'r')#读文件


  output=open(filename,'w')#写文件


  output=open(filename,'a')#追加写文件


  遍历文件夹操作


  importos


  forroot,dirs,filesinos.walk(path,topdown=False):


  #hanldefile


  fornameinfiles:


  ifname[:-3]='exe':


  printname


  #删除文件


  top='mydata/'


  forroot,dir,filesinos.walk(top,topdown=False):


  fornameinfiles:


  os.remove(os.path.join(root,name))


  os.rmdir('mydata')


  os.mkdir('mydata')


  列出文件


  importos


  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中是如何实现的:


  importos


  importsqlite


  classBlob:


  """Automaticallyencodeabinarystring."""


  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("CREATETABLEt(bBLOB);")


  s="\0"*50+"'"*50


  cursor.execute("INSERTINTOtVALUES(%s);",Blob(s))


  cursor.execute("SELECTbFROMt;")


  b=cursor.fetchone()[0]


  assertb==s#bisautomaticallydecoded


  db.close()


  os.remove("test.db")


  以上就是为大家整理的常用Python代码。

专栏文章内容及配图由作者撰写发布,仅供工程师学习之用,如有侵权或者其他违规问题,请联系本站处理。 联系我们

关键词:

相关推荐

端到端来了,激光雷达就没有明天了吗?

英飞凌亮相2024 RT-Thread开发者大会,加速AI进化,共探智能硬件创新之路

美研制新概念载人小型深潜器

视频 2010-01-14

村田新品 | 配备MCU、支持多无线标准的微小型通信模块

恩智浦一体化Matter解决方案,赋能自动化家居智能能源管理!

高频、薄型,且可像折纸一样弯曲加工的村田多层LCP基板

Vishay HV 系列高压 MLCC 赋能工业应用

面向21世纪的对陆火力支援舰炮技术

视频 2010-01-14

美研制新型CEV载人航天器

视频 2010-01-14

比亚迪为什么没有拿下电耗水平领先的标签?

电子技术如何助力高铁节能?

美批准建造首批DD(X)驱逐舰

视频 2010-01-14

美研究“多箭一星”发射技术

视频 2010-01-14

Vishay安规电容-汽车EMI解决方案的优质选择

汽车电子 2025-01-10

AURIX™ TC4x网络安全架构及对ISO/SAE 21434的支持

汽车电子 2025-01-10
更多 培训课堂
更多 焦点
更多 视频

技术专区