读取txt,无需引入任何包:
1 user_file = open('user_info.txt','r') 2 lines = user_file.readlines() 3 user_file.close() 4 5 for line in lines: 6 mail = line.split(',')[0] 7 username = line.split(',')[1] 8 pwd = line.split(',')[2] 9 print(mail,username,pwd)
user_info.txt
www.126.com,user1,pwd1
mail.163.com,user2,pwd2
mail.qq.com,user3,pwd3
读取csv,引入csv(使用wps或office创建excel另存为csv,不能擅自改后缀):
1 import csv 2 3 data = csv.reader( open('csv_read.csv', 'r') ) 4 5 for user in data: 6 print(user) 7 print('url = ',user[0],' | user = ',user[1], ' | pwd = ', user[2])
读取XML,引入xml.dom包(
node.firstChild.data获取文本
):
1 from xml.dom import minidom 2 3 try: 4 dom = minidom.parse('data_info.xml') 5 6 root = dom.documentElement 7 8 print(root.nodeName) 9 print(root.nodeValue) 10 print(root.nodeType) 11 print(root.ELEMENT_NODE) 12 13 browser = root.getElementsByTagName('browser') 14 print(browser[0].firstChild.data) 15 16 browser2 = root.getElementsByTagName('browser2') 17 print(browser2[0].firstChild.data) 18 19 mails = root.getElementsByTagName('mail') 20 for mail in mails: 21 print(mail.firstChild.data) 22 23 users = root.getElementsByTagName('user') 24 i = 0 25 for user in users: 26 name = user.getElementsByTagName('name') 27 i += 1 28 print(i,'---',name[0].firstChild.data) 29 pwd = user.getElementsByTagName('pwd') 30 print(i,'---',pwd[0].firstChild.data) 31 32 33 except BaseException as msg: 34 print(msg)
XML文件:
<info>
<base>
<platform>Windows</platform>
<platform2>Mac</platform2>
<platform3>liunx</platform3>
<browser>Firefox</browser>
<browser2>Chrome</browser2>
<browser3>IE</browser3>
</base>
<test>
<province>北京</province>
<province>广东</province>
<city>深圳</city>
<city>珠海</city>
<province>浙江</province>
<city>杭州</city>
</test>
<user>
<mail>mail.qq.com</mail>
<name>user1</name>
<pwd>pwd1</pwd>
</user>
<user>
<mail>www.126.com</mail>
<name>user2</name>
<pwd>pwd2</pwd>
</user>
<user>
<mail>mail.163.com</mail>
<name>user3</name>
<pwd>pwd3</pwd>
</user>
</info>