解析文件夹中的文件时内存错误

0 投票
1 回答
606 浏览
提问于 2025-04-17 21:54

我在用 Python 2.7

这是我用来解析文件夹里文件的代码

import linecache
import glob
path = r"G:\test\folder1"
Key = '''testresult="NOK"'''
Files = glob.glob(path+'\*.xml')
for FileName in Files:
    Loop_Count = 1
    while Loop_Count!= 50:
        Line_Read = linecache.getline(FileName, Loop_Count)
        if (Key in Line_Read):
            a = FileName.split('\\')
            b = len(a)-1
            print a[b]
            break
        elif(Loop_Count == 49):
            pass
        Loop_Count = Loop_Count+1
print "Completed"

如果 folder1 里有很多文件,我就会遇到内存错误

Traceback (most recent call last):
  File "C:\Users\whoKnows\Desktop\test_Check111.py", line 10, in <module> Line_Read = linecache.getline(FileName, Loop_Count)
  File "C:\Python27\lib\linecache.py", line 14, in getline
lines = getlines(filename, module_globals)
  File "C:\Python27\lib\linecache.py", line 40, in getlines
return updatecache(filename, module_globals)
  File "C:\Python27\lib\linecache.py", line 128, in updatecache
lines = fp.readlines()
MemoryError

我觉得这是因为我打开了所有的文件来读取,但没有把它们关闭。有人能告诉我在使用 glob 的时候怎么关闭文件吗?

1 个回答

1

MemoryError的意思是你的内存不够用了。可能是你一次性把所有文件都加载到内存里了。试着用linecache.clearcache()来删除那些不再需要的行。

撰写回答