欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 汽车 > 新车 > Python读写文本、图片、xml

Python读写文本、图片、xml

2025/7/3 19:30:09 来源:https://blog.csdn.net/weixin_44875787/article/details/139969218  浏览:    关键词:Python读写文本、图片、xml

Python操作文本、图片、xml

  • 1.Python读写文本
    • 1.1文本读取
    • 1.2文本写入
  • 2.Python读取、显示图片
  • 3.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中内容。

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

2.运行结果:

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.运行结果:

你好呀!!!,wxlProcess finished with exit code 0

1.2文本写入

f = open("helloworld.txt",mode="w")
f.write("我们朋友!!!")
f.close()f = open("helloworld.txt",mode="r")
data = f.read()
print(data)

运行结果:

我们朋友!!!Process finished with exit code 0

2.Python读取、显示图片

使用PIL家族读取图片。

from PIL import Imageimg = Image.open("./5.jpg")
img.show()

显示效果:
请添加图片描述

3.Python读写Xml

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)

运行结果:

output.xml文件内容
<?xml version='1.0' encoding='UTF-8'?>
<root><学生1 年龄="20">小明</学生1><学生2 年龄="25">小王</学生2></root>
学生1 {'年龄': '20'}
学生2 {'年龄': '25'}Process finished with exit code 0

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词