Python 3.X 基础(二)

对象

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)





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值