网站首页 > 技术文章 正文
第一种:使用 open
常规操作
with open('data.txt') as fp:
content = fp.readlines()
第二种:使用 fileinput
使用内置库 fileinput
import fileinput
with fileinput.input(files=('data.txt',)) as file:
content = [line for line in file]
第三种:使用 filecache
使用内置库 filecache,你可以用它来指定读取具体某一行,或者某几行,不指定就读取全部行。
import linecache
content = linecache.getlines('werobot.toml')
第四种:使用 codecs
使用 codecs.open 来读取
import codecs
file=codecs.open("README.md", 'r')
file.read()
如果你还在使用 Python2,那么它可以帮你处理掉 Python 2 下写文件时一些编码错误,一般的建议是:
在 Python 3 下写文件,直接使用 open
第五种:使用 io 模块
使用 io 模块的 open 函数
import io
file=io.open("README.md")
file.read()
io.open和open是同一个函数
Python 3.9.2 (default, Feb 28 2021, 17:03:44)
[GCC 10.2.1 20210110] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import os
>>> (open1:=open) is (open2:=os.open)
False
>>> import io
>>> (open3:=open) is (open3:=io.open)
True
第六种:使用 os 模块
os 模块也自带了 open 函数,直接操作的是底层的 I/O 流,操作的时候是最麻烦的
>>> import os
>>> fp = os.open("hello.txt", os.O_RDONLY)
>>> os.read(fp, 12)
b'hello, world'
>>> os.close(fp)
猜你喜欢
- 2025-01-06 3分钟教会你用Python读取MySQL中的数据
- 2025-01-06 Python高效管理JSON文件:读写、更新、删除全攻略
- 2025-01-06 读取txt、doc、docx、pdf文件——python
- 2025-01-06 20 天学 Python 文件操作:Day 2 深入理解文件读取方法
- 2025-01-06 python 利用python读取DOC文件
- 2025-01-06 一日一技:在Python中逐行读取文件
- 2025-01-06 python中读取图片的6种方式
- 2025-01-06 Python读写docx文件
- 2025-01-06 Python 文件操作全指南:从读写到高级操作
- 2025-01-06 python读取文件
- 05-25Python 3.14 t-string 要来了,它与 f-string 有何不同?
- 05-25Python基础元素语法总结
- 05-25Python中的变量是什么东西?
- 05-25新手常见的python报错及解决方案
- 05-2511-Python变量
- 05-2510个每个人都是需要知道Python问题
- 05-25Python编程:轻松掌握函数定义、类型及其参数传递方式
- 05-25Python基础语法
- 257℃Python短文,Python中的嵌套条件语句(六)
- 257℃python笔记:for循环嵌套。end=""的作用,图形打印
- 256℃PythonNet:实现Python与.Net代码相互调用!
- 251℃Python操作Sqlserver数据库(多库同时异步执行:增删改查)
- 251℃Python实现字符串小写转大写并写入文件
- 106℃原来2025是完美的平方年,一起探索六种平方的算吧
- 90℃Python 和 JavaScript 终于联姻了!PythonMonkey 要火?
- 81℃Ollama v0.4.5-v0.4.7 更新集合:Ollama Python 库改进、新模型支持
- 最近发表
- 标签列表
-
- python中类 (31)
- python 迭代 (34)
- python 小写 (35)
- python怎么输出 (33)
- python 日志 (35)
- python语音 (31)
- python 工程师 (34)
- python3 安装 (31)
- python音乐 (31)
- 安卓 python (32)
- python 小游戏 (32)
- python 安卓 (31)
- python聚类 (34)
- python向量 (31)
- python大全 (31)
- python次方 (33)
- python桌面 (32)
- python总结 (34)
- python浏览器 (32)
- python 请求 (32)
- python 前端 (32)
- python验证码 (33)
- python 题目 (32)
- python 文件写 (33)
- python中的用法 (32)