本章学习目的
学会如何操作读写文本文件,操作数组,操作json,操作xml
一、读文本文件
代码: 】
#!/usr/bin/python
# -*- coding: UTF-8 -*-
# 读取文件,指的是一般文本文件,比如txt或者csv结尾的文件
def read_file(file_name):
# 尝试打开文件,并读取文件里的内容。为了严谨使用try finally。因为文件可能不存在也可能有其他异常,比如文件被占用,IO异常等
try:
# 第一步,定义个变量f,打开{file_name}这个文件,并且只读,并将其赋值给f
f = open(file_name, 'r')
# 第二步,读取该文件所有内容
print(f.read())
finally:
# 不管前面到第几步,最终都会执行
# 如果这个文件读取成功,必须在结尾关闭对该文件的读取
if f:
f.close()
# 和上面的功能一样,只是写法上更加优雅
def read_file_gracefully(file_name):
with open(file_name, 'r') as f:
print(f.read())
# 有时我们对行做一些处理再输出,可以这样写
def read_file_inline(file_name):
with open(file_name, 'r') as f:
array = f.readlines()
for i in range(0, len(array)):
array[i] = array[i].rstrip('\n')
print(f'这一行数据是:{array[i]}')
read_file('../resources/test.csv')
read_file_gracefully('../resources/test.csv')
read_file_inline('../resources/test.csv')
执行结果
二、写文本文件
代码:
#!/usr/bin/python
# -*- coding: UTF-8 -*-
# 写入文件,指的是一般文本文件,比如txt或者csv结尾的文件
def write_file(file_name):
try:
# 第一步,定义个变量f,打开{file_name}这个文件,并且可写,并将其赋值给f
f = open(file_name, 'w')
f.write('Hello, world!')
finally:
if f:
f.close()
def write_file_gracefully(file_name):
with open(file_name, 'w') as f:
f.write('Hello, world gracefully!')
def read_file(file_name):
print('---刚写入内容为---')
with open(file_name, 'r') as f:
print(f.read())
write_file_path = '../resources/write_test.txt'
write_file(write_file_path)
read_file(write_file_path)
write_file_gracefully(write_file_path)
read_file(write_file_path)
执行结果:
文本文件 write_test.txt内容
三、操作数组
前置依赖
安装numpy,在终端安装
pip3 install numpy
代码:
#!/usr/bin/python
# -*- coding: UTF-8 -*-
# numpy需要安装的,该库提供多元数组功能,比普通的数组功能强大很多
# 安装方法
# pip3 install numpy 或 pip3 install numpy -i https://pypi.tuna.tsinghua.edu.cn/simple/
# 引入numpy后续用np代表numpy
import numpy as np
# 预期打印
# [1 2 3]
a = np.array([1, 2, 3])
print(a)
# 输出[1, 7)中的整数,每次步长为1
start = 1
end = 7
step = 1
# 预期打印
# [1 2 3 4 5 6]
print('----输出[1, 7)中的整数,每次步长为1---')
print(np.arange(start, end, step, dtype=np.int16))
# 输出[1, 7)中的整数,每次步长为2
step = 2
# 预期打印
# [1 3 5]
print('----输出[1, 7)中的整数,每次步长为2---')
print(np.arange(start, end, step, dtype=np.int16))
# 输出[0, 12)中的整数,输出格式3行4列
# 预期打印
# [[ 0 1 2 3]
# [ 4 5 6 7]
# [ 8 9 10 11]]
print('----输出[0, 12)中的整数,输出格式3行4列---')
print(np.arange(12).reshape(3, 4))
执行结果
四、操作json
代码:
#!/usr/bin/python
# -*- coding: UTF-8 -*-
# 导引,要使用不同的格式,如json,需要更快的方式去做转换
# 本来就有json这个库,直接
import json
'''
1. 打印one_person这个json对象,并格式化输出,输出时,锁进空格为4
预期输出
{
"name": "Jake",
"age": 20
}
'''
one_person = {"name": "Jake", "age": 20}
print('---打印one_person---缩进4')
print(json.dumps(one_person, indent=4))
print('---打印one_person---缩紧4,且key值排序')
print(json.dumps(one_person, sort_keys=True, indent=4))
'''
2. str转json对象
'''
result = json.loads('{"name":"Tom", "age":23}')
print('---打印result---')
print(result)
print('---打印test.json文件中的内容---')
with open("../resources/test.json", "r", encoding='utf-8') as f:
print(f.read())
执行结果:
五、操作xml
代码:
#!/usr/bin/python
# -*- coding: UTF-8 -*-
# 导引,要使用不同的格式,如json,需要更快的方式去做转换
import os
import xml.sax
import xml.dom.minidom
# xml_str = '<collection shelf="New Arrivals">'\
# '<movie title="Enemy Behind">'\
# '<type>War, Thriller</type>'\
# '<format>DVD</format>'\
# '</movie>'\
# '</collection>'
# with open("../resources/movie.xml", "r", encoding='utf-8') as f:
# print(f.read())
DOMTree = xml.dom.minidom.parse("../resources/movie.xml")
collection = DOMTree.documentElement
if collection.hasAttribute("shelf"):
print("Root element : %s " % collection.getAttribute("shelf"))
movies = collection.getElementsByTagName("movie")
for movie in movies:
if movie.hasAttribute("title"):
print("标题 title : %s" % movie.getAttribute("title"))
# 获取所有<type>标签中第一个出现的type
type = movie.getElementsByTagName("type")[0]
# 打印该type节点下的内容
print("类型 type : %s\n" % type.childNodes[0].data)
执行结果: