从大文件中读取单个字节

Jas*_*ray 5 python file

我有这个函数,我想从大文件中读取一个字节.唯一的问题是,在一定量的文件读取后,PC上的内存会从稳定的1.5gb跳到4gb以上,具体取决于文件读取的数量.(我打破80个文件,因为更高的会崩溃我的电脑)

我想要的只是得到1个字节,而不是整个文件.请帮忙.

    def mem_test():
        count = 0
        for dirpath, dnames, fnames in scandir.walk(restorePaths[0]):
            for f in fnames:
                if 'DIR.EDB' in f or 'PRIV.EDB' in f:
                    f = open(os.path.join(dirpath, f), 'rb')
                    f.read(1) #Problem line!
                    f.close()
                    if count > 80:
                        print 'EXIT'
                        sys.exit(1)                    
                    count += 1
mem_test()
Run Code Online (Sandbox Code Playgroud)

Bri*_*ian -1

为了解决内存问题,我认为您需要使用生成器:

def mem_test():
    for dirpath, dnames, fnames in scandir.walk(restorePaths[0]):
        for f in fnames:
            if 'DIR.EDB' in f or 'PRIV.EDB' in f:
                with open(os.path.join(dirpath, f), 'rb') as f:
                    yield f.read(1) #Problem line!

results = [x for x in mem_test()]
Run Code Online (Sandbox Code Playgroud)