扣丁学堂为你总结Python常用代码大全

2017-12-27 11:53:42 983浏览

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




       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代码,想要学习Python的小伙伴可以选择扣丁学堂,扣丁学堂不仅有专业的老师,还有与时俱进的课程体系,更有大量的Python视频教程供学员观看学习,心动的小伙伴抓紧时间行动吧。扣丁学堂Python技术交流群:279521237。

关注微信公众号获取更多的学习资料


查看更多关于“Python开发资讯的相关文章>>

标签: Python培训 python视频教程 Python开发工程师

热门专区

暂无热门资讯

课程推荐

微信
微博
15311698296

全国免费咨询热线

邮箱:codingke@1000phone.com

官方群:148715490

北京千锋互联科技有限公司版权所有   北京市海淀区宝盛北里西区28号中关村智诚科创大厦4层
京ICP备12003911号-6   Copyright © 2013 - 2019

京公网安备 11010802030908号