Python read TXT, CSV, xml

table of Contents

Read TXT

Read CSV

Read xml


  • Read TXT

First, clarify the several methods used when reading the txt file:

  • read (): read the entire file
  • readline (): read a line of data
  • readlines (): read all lines of data
  • Open the document: open
user_file=open("xxx","r")#找到文件所在的地方**注意目录的形式\\,这块容易出错
lines=user_file.readlines()#按所有行读取文本中的数据
user_file.close()
#遍历所有行的数据并存储为line
for line in lines:
     username=line.split(",")[0] #将拆分出来的第一部分的值放在这
     password=line.split(",")[1] #将拆分出来的第二部分的值放在这
     print(username,password)

split can split a string into two parts by a certain character;

For example, there are two lines of zhangsan, 123 in the text. Can be split into two parts by split (","); split (""), split (";") can also be used

                      lysis, 231

  • Read CSV

  • reader
  • Open the document: open
import csv  #导入CSV包
date=csv.reader(open("xxx","r"))#打开文件
for user in date:
    print(user[0])
  • Read xml

  • Open the document: parse

xml file

<?xml version="1.0" encoding="utf-8"?><!--格式声明-->
<!--根元素-->  
<info>    
	<base><!--子元素-->
	<platform>windows</platform>
	<platform>liux</platform>
	<browser>chrome</browser>
	<url>http://localhost:8080/jforum-2.6.2/forums/list.page</url>
		<login username="admin" password="123456"/>
		<login username="guest" password="456788"/>
	</base>
	<test>
		<province>北京</province>
		<province>上海</province>
		<city>杭州</city>
		<province>陕西</province>
		<city>西安</city>
		<city>渭南</city>
	</test><!--根元素-->  
</info>

#用python读取xml文件
from xml.dom import minidom  #导入minidom模块
dom=minidom.parse("xxx")#打开文档
root=dom.documentElement
print(root.nodeName)##节点名称
print(root.nodeValue)##节点值
print(root.nodeType)##节点类型
print(root.ELEMENT_NODE)

##xml中取出的数据都是以数组的形式保存的,因此引用变量的时候都必须以素数组的形式
#获取标签名
tagname=root.getElementsByTagName('platform')##getElementsByTagName(tagname) 方法可返回带有指定标签名的对象的集合。
print (tagname[0].tagName)  ##在xml中有多个tagname为platform的元素。取出一组标签中的第一个

#获取标签名里面的值(文本形式的)
print(tagname[0].firstChild.data)

#获取标签的属性值
logins=root.getElementsByTagName('login')
print(logins[0].getAttribute('username'))
logins=root.getElementsByTagName('login')
print(logins[0].getAttribute('password'))

 

 

 

 

Published 22 original articles · praised 5 · visits 1040

Guess you like

Origin blog.csdn.net/weixin_37018468/article/details/105412819