【问题标题】:Opening multiple files and assign them to a dictionary打开多个文件并将它们分配给字典
【发布时间】:2014-11-26 00:02:44
【问题描述】:

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

【问题讨论】:

    标签: python file dictionary


    【解决方案1】:

    你可以像这样使用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 字典会消耗大量内存。最好一次打开并阅读它们,而不是一次全部阅读。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-02
      • 1970-01-01
      • 1970-01-01
      • 2012-12-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多