0

我正在使用 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"

如果文件夹 1 有很多文件,我会收到内存错误

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 时关闭文件。

4

1 回答 1

1

MemoryError表示您的内存已用完。您可能一次将所有文件加载到内存中。尝试使用 删除不再需要的行linecache.clearcache()

于 2014-03-12T09:17:23.863 回答