Python 3.X 基础(二)

来源:互联网 发布:管家婆软件有哪几种 编辑:程序博客网 时间:2024/05/19 11:38

对象

class Student():    def __init__(self,name,city):        self.name=name        self.city=city        print("My name is %s and come from %s" %(name,city))            def talk(self):        print("hello world!")        student1=Student('jack','Beijing')student1.talk()
time模块
from time import sleep,ctimeprint(ctime())sleep(3)

异常捕获

try:    filename=input("please input filename:")    open("%s.txt" %filename)except FileNotFoundError:    print("%s.txt file not found" %filename)    try:    print(stu)except BaseException:    print("stu not defined")

读.txt文件

f=open('stu_info.txt','r')lines=f.readlines()for line in lines:    print(line.split(',')[0])
读写.csv文件
import csvcsv_file=csv.reader(open('stu_info.csv'),'r')for line in csv_file:    print(line)stu=['Marry',28,'shanghai']stu1=['Rom',23,'beijing']out=open('stu_info.csv','a',newline='')csv_write=csv.writer(out,dialect='excel')csv_write.writerow(stu)csv_write.writerow(stu1)
读.xml文件

from xml.dom import minidomdom=minidom.parse('stu_info.xml')root=dom.documentElement#获取节点值names=root.getElementsByTagName('name')ages=root.getElementsByTagName('age')citys=root.getElementsByTagName('city')for i in range(4):    print(names[i].firstChild.data)    print(ages[i].firstChild.data)    print(citys[i].firstChild.data)#获取节点属性logins = root.getElementsByTagName('login')username = logins[0].getAttribute('username')password = logins[0].getAttribute('password')#获取节点名,类型,值tags = root.getElementsByTagName('student')print(tags[0].nodeName)print(tags[0].nodeType)print(tags[0].nodeValue)





原创粉丝点击