Python读写文本、图片、xml

Python操作文本、图片、xml

(1)Python读写文本
(2)Python读取、显示图片
(3)Python读写Xml

1.Python读写文本

新建helloworld.txt,创建file.py文件用于读写helloworld.txt。

1.1文本读取

1.在helloworld.txt中写入内容"你好呀!!!,wxl"。在file.py中编写程序读取helloworld.txt中内容。

cpp 复制代码
f = open("helloworld.txt",mode="r")
data = f.read()
print(data)

2.运行结果:

cpp 复制代码
Traceback (most recent call last):
  File "/home/tarena/PycharmProjects/爬虫/file.py", line 1, in <module>
    f = open("helloworld.txt",mode="r")
FileNotFoundError: [Errno 2] No such file or directory: 'helloworld.txt'

3.在右上交选择file->Edit Configurations,修改工作路径(working directory)到当前文件夹:

4.运行结果:

cpp 复制代码
你好呀!!!,wxl

Process finished with exit code 0

1.2文本写入

cpp 复制代码
f = open("helloworld.txt",mode="w")
f.write("我们朋友!!!")
f.close()

f = open("helloworld.txt",mode="r")
data = f.read()
print(data)

运行结果:

cpp 复制代码
我们朋友!!!

Process finished with exit code 0

2.Python读取、显示图片

使用PIL家族读取图片。

cpp 复制代码
from PIL import Image

img = Image.open("./5.jpg")
img.show()

显示效果:

3.Python读写Xml

cpp 复制代码
from lxml import etree

#写入XML文件
# 创建根元素和子元素
root = etree.Element('root')
child1 = etree.SubElement(root, '学生1')
child1.set('年龄', '20')
child1.text = '小明'
child2 = etree.SubElement(root, '学生2')
child2.set('年龄', '25')
child2.text = '小王'

# 将元素写入文件
tree = etree.ElementTree(root)
tree.write('output.xml', encoding='utf-8', xml_declaration=True)

# 解析XML文件
tree = etree.parse('output.xml')
root = tree.getroot()  # 获取根元素
for child in root:  # 遍历子元素
    print(child.tag, child.attrib)

运行结果:

cpp 复制代码
output.xml文件内容
<?xml version='1.0' encoding='UTF-8'?>
<root><学生1 年龄="20">小明</学生1><学生2 年龄="25">小王</学生2></root>
cpp 复制代码
学生1 {'年龄': '20'}
学生2 {'年龄': '25'}

Process finished with exit code 0
相关推荐
紫雾凌寒37 分钟前
计算机视觉 |解锁视频理解三剑客——TimeSformer
python·深度学习·神经网络·计算机视觉·transformer·timesformer
程序员杰哥1 小时前
测试用例详解
自动化测试·软件测试·python·功能测试·测试工具·职场和发展·测试用例
go54631584657 小时前
本地部署 GitHub 上的 Python 人脸识别项目
开发语言·python·github
FreakStudio8 小时前
手把手教你用 MicroPython 玩转幻尔串口舵机,代码+教程全公开
python·嵌入式·大学生·面向对象·技术栈·电子diy·电子计算机
tekin8 小时前
基于 Python 开发在线多人游戏服务器案例解析
服务器·python·游戏·在线多人游戏服务器
让学习成为一种生活方式10 小时前
libGL.so.1: cannot open shared object file: No such file or directory-linux022
linux·开发语言·python
java1234_小锋10 小时前
一周学会Flask3 Python Web开发-Jinja2模板继承和include标签使用
python·flask·flask3
图书馆钉子户10 小时前
from flask_session import Session 为什么是Session(app)这么用?
python·flask·mybatis
一只蜗牛儿11 小时前
Sherpa-ONNX:说话人识别与语音识别自动开启(VAD)+ Python API 完整指南
人工智能·python·语音识别
结衣结衣.11 小时前
【OpenCV】入门教学
图像处理·人工智能·python·opencv