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
相关推荐
Patrick在香港1 分钟前
第 16,216 次连接之后,它不干了
python·网络编程·socket·tcp·连接池
我命由我123455 分钟前
Python 开发 - Python 虚拟环境
运维·开发语言·后端·python·http·https·java-ee
云和数据.ChenGuang19 分钟前
LLM大模型对接本地Ollama部署模型
开发语言·人工智能·python·langchain
云和数据.ChenGuang1 小时前
光哥说Python 循环导入(Circular Import)深度解析:成因、排查与解决方案
开发语言·前端·人工智能·python·langchain
TomEval1 小时前
【测AI】第16篇:模型公平性与可解释性测试 — AI 的偏见与黑箱
人工智能·python·功能测试·ai·测试用例
田里的水稻1 小时前
FA_CNN卷积神经网络四---线性层及其拉平PyTorch
人工智能·pytorch·python·深度学习·神经网络·cnn
钱栈up2 小时前
GitHub热榜上手|Claude插件:4.3万星官方目录
python·开源·github
青春不朽5122 小时前
Python 的 list append 为什么是均摊 O(1)?拆开过度分配那张表,看容量翻倍背后的暗账
java·python·list
小羊没烦恼!2 小时前
.NET 11 Runtime Async 详解
java·运维·开发语言·javascript·python
染指11103 小时前
152.Agent-LangGraph-Command的参数
人工智能·python·langchain·agents