如何在Python中从文件中逐个读取字符?

96

在Python中,给定一个文件的名称,如何编写一个循环,每次通过循环读取一个字符?

15个回答

0

结合其他答案的优点,这里提供一种更加简洁快速且不易受长文件/行影响的解决方案:

import functools as ft, itertools as it

with open(path) as f:
    for c in it.chain.from_iterable(
        iter(ft.partial(f.read, 4096), '')
    ):
        print(c)

0
f = open('hi.txt', 'w')
f.write('0123456789abcdef')
f.close()
f = open('hej.txt', 'r')
f.seek(12)
print f.read(1) # This will read just "c"

3
欢迎来到Stackoverflow!你应该详细说明 - 为什么这是一个答案? - davidkonrad

0
os.system("stty -icanon -echo")
while True:
    raw_c = sys.stdin.buffer.peek()
    c = sys.stdin.read(1)
    print(f"Char: {c}")

0
补充一下,如果你正在读取一个包含非常大的行的文件,这可能会耗尽你的内存,那么你可以考虑将它们读入缓冲区,然后逐个字符地输出。
def read_char(inputfile, buffersize=10240):
    with open(inputfile, 'r') as f:
        while True:
            buf = f.read(buffersize)
            if not buf:
                break
            for char in buf:
                yield char
        yield '' #handle the scene that the file is empty

if __name__ == "__main__":
    for word in read_char('./very_large_file.txt'):
        process(char)

-2
#reading out the file at once in a list and then printing one-by-one
f=open('file.txt')
for i in list(f.read()):
    print(i)

虽然这可能回答了作者的问题,但它缺少一些解释性的词语和文档链接。裸代码片段没有周围的一些短语是不太有帮助的。您也可以在如何撰写好的答案中找到很多帮助。请编辑您的答案。 - hellow
你不需要将其转换为列表。 - user240515
将类型转换为列表会不必要地将整个内容加载到内存中,这可能会导致OOM和/或低效缓冲。OP问如何“一次读取一个字符”,因此这并没有回答问题。 - Douglas Myers-Turnbull

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接