python - Python中有没有办法逐个读取文本文件?
问题描述
我需要处理一个BIG文本文件,其中包含以 ASCII 表示的空格分隔的浮点数:
1.0012 0.63 18.201 -0.7911 92.2869 ...
如何使用内置 Python 工具逐一读取这些数字(不是整个文件,也不是逐行)?作为示例,解决此任务的 C 源代码如下所示:
float number;
FILE *f = fopen ("bigfile.txt", "rt");
while (!feof (f)) {
fscanf (f, "%f", &number);
/* ... processing the number here ... */
}
fclose (f);
解决方案
您可以尝试逐字符读取文件,将块大小指定为 1,然后识别单词是否完整。
with open('file', 'r') as openedFile:
for chunk in iter(partial(openedFile.read, 1), b''):
...
有用的链接:
https://docs.python.org/3/tutorial/inputoutput.html#methods-of-file-objects
推荐阅读
- ssh - 使用 gitlab-ci 使用 scp 部署文件只有在被标签触发时才会失败
- triggers - IFTTT ASUS Trigger,Device Connected 下拉列表仅显示 1 个设备并在整个列表中重复
- javascript - 轮子内的 HTML5 画布文本方向圆圈
- elasticsearch - Elasticsearch:如果其中一个批量更新失败会发生什么?
- php - 如何用零舍入/格式化长数字?
- cxf - BSP:R5417: Any SIG_KEY_INFO MUST contain a SECURITY_TOKEN_REFERENCE child element
- android - 为什么在使用 Firebase Recycler View Adapter 时出现调用目标异常?
- mautic - 使用 Mautic API 向现有联系人添加标签
- java - 将查询结果打印到 jsp 表 Java Spring MVC jsp
- python-asyncio - asyncio 中的非阻塞套接字 connect()