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
相关推荐
计算机毕业设计木哥17 分钟前
计算机毕设选题:基于Python+Django的B站数据分析系统的设计与实现【源码+文档+调试】
java·开发语言·后端·python·spark·django·课程设计
中等生1 小时前
Pandas 与 NumPy:数据分析中的黄金搭档
后端·python
用户8356290780511 小时前
Python查找替换PDF文字:告别手动,拥抱自动化
后端·python
星哥说事1 小时前
Python自学12 — 函数和模块
开发语言·python
THMAIL2 小时前
深度学习从入门到精通 - 迁移学习实战:用预训练模型解决小样本难题
人工智能·python·深度学习·算法·机器学习·迁移学习
和小胖11223 小时前
第一讲 Vscode+Python+anaconda 安装
python
和小胖11223 小时前
第二讲 Vscode+Python+anaconda 高阶环境配置
ide·vscode·python
小胖墩有点瘦3 小时前
【基于yolo和web的垃圾分类系统】
人工智能·python·yolo·flask·毕业设计·课程设计·垃圾分类
站大爷IP4 小时前
Python实现简易成语接龙小游戏:从零开始的趣味编程实践
python
PP东4 小时前
Pyhton基础之多继承、多态
开发语言·python