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 - 深度学习训练过程使用matplotlib.pyplot实时动态显示loss和acc曲线 阅读2002次,点赞0次
- Python - 使用with open as 读写文件 阅读1350次,点赞0次
- Python - 配置Yolov5出现ImportError: cannot import name 'PILLOW_VERSION' from 'PIL'错误 阅读986次,点赞0次
- Python - 语音识别文本相似性度量库jiwer,可计算文字错误率WER、匹配错误率MER等相似性度量指标 阅读851次,点赞0次
- Python - ModuleNotFoundError: No module named 'skimage' 阅读101次,点赞0次
- Python - 使用ffmepg批量转换某个文件夹以及所有子文件夹下所有的视频,修改其帧率/码率/分辨率到另一文件夹,并保留原有文件夹结构 阅读2423次,点赞0次
- Python - list/numpy/pytorch tensor相互转换 阅读1442次,点赞0次
- Python - 使用Python+websockets时报错:AttributeError: module 'websockets' has no attribute 'serve' 阅读1392次,点赞0次
- Python - 类对象/列表/元祖/字典判空的方法 阅读2050次,点赞0次
- Python - 爬取直播吧首页重要赛事赛程信息 阅读96次,点赞0次
全站随机文章推荐
- 资源分享 - 物理渲染-从理论到实践 第2版,Physically Based Rendering From Theory To Implementation(Second Edition) 中文版PDF下载 阅读1674次,点赞0次
- 资源分享 - Efficient Illumination Algorithms for Global Illumination In Interactive and Real-Time Rendering英文PDF下载 阅读2377次,点赞0次
- OpenCV/FFmpeg - 使用FFmpeg编码OpenCV中的BGR视频流为H264视频流以及解码H264视频流为OpenCV中的BGR视频流 阅读959次,点赞1次
- Python - 使用onnxruntime加载和推理onnx模型 阅读118次,点赞0次
- Centos7 编译C++项目错误解决 : terminate called after throwing an instance of 'std::regex_error' 阅读2285次,点赞1次
- Duilib - RichEdit作为日志输出控件,更新日志内容后并自动跳到最后一行 阅读1881次,点赞2次
- Duilib - Edit编辑控件输入文字时编辑框背景颜色不是所设置的背景颜色的问题 阅读291次,点赞1次
- WordPress - home_url()函数,获取网站主页url链接 阅读687次,点赞0次
- C++ - 线程安全的std::cout 阅读1754次,点赞0次
- Pytorch - 内置的CTC损失函数torch.nn.CTCLoss参数详解与使用示例 阅读662次,点赞0次
评论
164