python读取txt、csv、xml

时间:2023-12-12 20:35:14

读取txt,无需引入任何包:

 user_file = open('user_info.txt','r')
lines = user_file.readlines()
user_file.close() for line in lines:
mail = line.split(',')[0]
username = line.split(',')[1]
pwd = line.split(',')[2]
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,不能擅自改后缀):

 import csv

 data = csv.reader( open('csv_read.csv', 'r') )

 for user in data:
print(user)
print('url = ',user[0],' | user = ',user[1], ' | pwd = ', user[2])

python读取txt、csv、xml

读取XML,引入xml.dom包(

node.firstChild.data获取文本

):

 from xml.dom import minidom

 try:
dom = minidom.parse('data_info.xml') root = dom.documentElement print(root.nodeName)
print(root.nodeValue)
print(root.nodeType)
print(root.ELEMENT_NODE) browser = root.getElementsByTagName('browser')
print(browser[0].firstChild.data) browser2 = root.getElementsByTagName('browser2')
print(browser2[0].firstChild.data) mails = root.getElementsByTagName('mail')
for mail in mails:
print(mail.firstChild.data) users = root.getElementsByTagName('user')
i = 0
for user in users:
name = user.getElementsByTagName('name')
i += 1
print(i,'---',name[0].firstChild.data)
pwd = user.getElementsByTagName('pwd')
print(i,'---',pwd[0].firstChild.data) except BaseException as msg:
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>