1 回答

TA貢獻1821條經驗 獲得超5個贊
您想先將一個文件讀入內存,然后將其存儲在一個文件集中。集合中的成員資格測試非常有效,遠比為第一個文件中的每一行循環遍歷第二個文件的行要有效得多。
然后,您只需要讀取第二個文件,然后逐行處理它并測試行是否匹配。
您保存在內存中的文件取決于的大小All.txt。如果它小于1000行,只需將其保留在內存中,然后將其與其他文件進行比較即可。如果All.txt確實很大,請為file1您的每個處理過程重新打開它,然后僅將其的前18行讀file1入內存,并將它們與中的每一行進行All.txt逐行匹配。
要僅讀取文件的18行,請使用itertools.islice();文件是可迭代的,并且islice()是選擇要讀取的行的子集的最簡單方法。
All.txt首先讀入內存:
from itertools import islice
with open ("c:/All.txt", "r") as all:
# storing lines without whitespace to make matching a little more robust
all_lines = set(line.strip() for line in all)
for filename in find_files('a-zA-Z0-9', '*.txt'):
with open(filename, "r") as file1:
for line in islice(file1, 18):
if line.strip() in all_lines:
# matched line
如果All.txt很大,請先將每個文件的那18行存儲在一個集中,然后重新打開All.txt并逐行處理:
for filename in find_files('a-zA-Z0-9', '*.txt'):
with open(filename, "r") as file1:
file1_lines = set(line.strip() for line in islice(file1, 18))
with open ("c:/All.txt", "r") as all:
for line in all:
if line.strip() in file1_lines:
# matched line
請注意,你不會有更改目錄中find_files(); os.walk()已經傳遞了目錄名稱。該fnmatch模塊還有一個.filter()方法,使用該方法可以循環files而不是fnmatch.fnmatch()單獨在每個文件上使用:
def find_files(directory, pattern):
directory = "c:\\TEST"
for root, dirs, files in os.walk(directory):
for basename in fnmatch.filter(files, pattern):
yield os.path.join(root, basename)
添加回答
舉報