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
相关推荐
wyiyiyi20 分钟前
【Web后端】Django、flask及其场景——以构建系统原型为例
前端·数据库·后端·python·django·flask
mit6.82436 分钟前
[1Prompt1Story] 滑动窗口机制 | 图像生成管线 | VAE变分自编码器 | UNet去噪神经网络
人工智能·python
没有bug.的程序员40 分钟前
JVM 总览与运行原理:深入Java虚拟机的核心引擎
java·jvm·python·虚拟机
甄超锋1 小时前
Java ArrayList的介绍及用法
java·windows·spring boot·python·spring·spring cloud·tomcat
阿华的代码王国1 小时前
【Android】RecyclerView复用CheckBox的异常状态
android·xml·java·前端·后端
AntBlack2 小时前
不当韭菜V1.1 :增强能力 ,辅助构建自己的交易规则
后端·python·pyqt
杜子不疼.4 小时前
《Python学习之字典(一):基础操作与核心用法》
开发语言·python·学习
myzzb5 小时前
基于uiautomation的自动化流程RPA开源开发演示
运维·python·学习·算法·自动化·rpa
TLuoQiu5 小时前
小电视视频内容获取GUI工具
爬虫·python
我叫黑大帅5 小时前
【CustomTkinter】 python可以写前端?😆
后端·python