首页 > 解决方案 > 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);

标签: pythonfile

解决方案


您可以尝试逐字符读取文件,将块大小指定为 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


推荐阅读