我想在Python中打开多个文件,并将它们作为值分配给字典。
我可以用open()
函数打开每个文件,但是如果我有1000个文件呢?!
它是这样的东西,但我需要一个循环打开这些文件,并分配给他们的文档字典!我想知道是否有人能帮我。你知道吗
f1 = open('doc1.txt', 'r').read()
f2 = open('doc2.txt', 'r').read()
f3 = open('doc3.txt', 'r').read()
f4 = open('doc4.txt', 'r').read()
f5 = open('doc5.txt', 'r').read()
f6 = open('doc6.txt', 'r').read()
f7 = open('doc7.txt', 'r').read()
f8 = open('doc8.txt', 'r').read()
f9 = open('doc9.txt', 'r').read()
f10 = open('doc10.txt', 'r').read()
documents = {'doc1':f1, 'doc2':f2, 'doc3':f3, 'doc4':f4, 'doc5':f5, 'doc6':f6, 'doc7':f7, 'doc8':f8, 'doc9':f9, 'doc10':f10}
可以使用for循环,如下所示:
但是请记住,如果文件很大,
documents
字典将消耗大量内存。最好是一次一个打开阅读,而不是一次全部阅读。你知道吗相关问题 更多 >
编程相关推荐