Python – 使用with open as 读写文件
本文作者:StubbornHuang
版权声明:本文为站长原创文章,如果转载请注明原文链接!
原文标题:Python – 使用with open as 读写文件
原文链接:https://www.stubbornhuang.com/1433/
发布于:2021年07月13日 21:11:42
修改于:2021年07月13日 21:11:42

1 Python文件读写模式

2 文件读取常用方法
方法 | 描述 |
---|---|
readline() | 读取一行 |
readline(2) | 读取前 2 个字符 |
read() | 读完文件后,指针在最尾处 |
write() | 写完文件后,指针在最尾处 |
tell() | 当前指针位置 |
seek(0) | 设置指针位置,0:文件头,1:当前,2:文件尾 |
flush() | 刷新 |
truncate() | 清空 |
truncate(10) | 从头开始,第 10 个字符后清空 |
close() | 关闭文件 |
encoding | 字符编码 |
name | 文件名 |
3 Python传统读写文件的方式
3.1 读文件
file = open('1.txt', 'r', encoding='UTF-8')
try:
file_content = file.read()
print(file_content)
finally:
file.close()
3.2 写文件
file = open('1.txt', 'w', encoding='UTF-8')
try:
file_bytes = file.write('1213\n哈哈哈')
print(file_bytes)
finally:
file.close()
4 使用with open … as 读写文件
使用上述传统的文件读写方式,容易忘记关闭文件,容易忘记对文件读写异常时忘记做处理,而with as方法可以自动关闭文件,无需手动关闭文件
4.1 读文件
with open('test.txt', 'r',encoding='UTF-8') as file1:
print(file1.read())
4.2 写文件
with open('test.txt','a',encoding='UTF-8') as file:
print('Hello world',file=file)
当前分类随机文章推荐
- Python - 使用flask_sockets库构建websocket服务器 阅读1275次,点赞0次
- Python - 运算符/ or // or %的含义和区别 阅读1207次,点赞0次
- Python - 各种包安装、导入问题总结 阅读809次,点赞0次
- Python - 运行YOLOv5出现AttributeError: module 'torchvision' has no attribute 'ops' 阅读122次,点赞0次
- Python - ModuleNotFoundError: No module named 'absl' 阅读222次,点赞0次
- 解决Python爬虫在爬资源过程中使用urlretrieve函数下载文件不完全且避免下载时长过长陷入死循环,并在下载文件的过程中显示下载进度 阅读2988次,点赞0次
- Python - 使用websockets库构建websocket服务器 阅读892次,点赞0次
- Python3爬虫 - requests库的requests.exceptions所有异常详细说明 阅读3347次,点赞1次
- Python - 判断一个字符串是否为json格式 阅读469次,点赞0次
- Python - 使用Opencv-Python库获取本机摄像头视频并保存为视频文件 阅读1587次,点赞0次
全站随机文章推荐
- 资源分享 - GPU Pro 360 - Guide to GPGPU 英文高清PDF下载 阅读1196次,点赞0次
- 资源分享 - Graphics Gems I 英文高清PDF下载 阅读1366次,点赞0次
- 资源分享 - GPU Pro 360 - Guide to Mobile Devices 英文高清PDF下载 阅读1337次,点赞0次
- C++11 - std::chrono - 使用std::chrono::duration_cast进行时间转换,hours/minutes/seconds/milliseconds/microseconds相互转换,以及自定义duration进行转换 阅读1206次,点赞0次
- MindSpore - LeNet5的MindSpore实现 阅读206次,点赞0次
- Mediapipe - 使用Mediapipe Holistic识别身体、手、面部全身关节点 阅读2550次,点赞1次
- OpenCV - 新建一个图片,并在图片上画由一点到另一点的直线,采用反走样形式 阅读2202次,点赞0次
- 资源分享 - OpenGL SuperBible - Comprehensive Tutorial and Reference (Fifth Edition) OpenGL蓝宝书第5版英文高清PDF下载 阅读814次,点赞0次
- Centos7 - 配置Go环境 阅读2065次,点赞1次
- Centos7 - nohup方式优雅的部署jar包 阅读1965次,点赞0次
评论
144