对象
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,ctime
print(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 csv
csv_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 minidom
dom=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)