打开多个文件并将其分配给词典

2024-09-29 19:33:06 发布

您现在位置:Python中文网/ 问答频道 /正文

我想在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}

Tags: 文件txtread字典doc1openf5f2
1条回答
网友
1楼 · 发布于 2024-09-29 19:33:06

可以使用for循环,如下所示:

documents = {}
for i in range(1, 11):
    i = str(i)
    with open('doc' + i + '.txt') as f:  # This closes the files when done.
        documents['doc' + i] = f.read()

但是请记住,如果文件很大,documents字典将消耗大量内存。最好是一次一个打开阅读,而不是一次全部阅读。你知道吗

相关问题 更多 >

    热门问题