【问题标题】:how to store the contents of files in arrays using python?如何使用python将文件的内容存储在数组中?
【发布时间】:2012-06-11 12:10:42
【问题描述】:

我有 5 个文本文件需要存储在数组中。我试过这样。

f=[]
f[0]=open('E:/cyg/home/Aiurea/workspace/nCompare5w5.txt','r')
f[1]=open('E:/cyg/home/Aiurea/workspace/nCompare5w10.txt','r')
f[2]=open('E:/cyg/home/Aiurea/workspace/nCompare5w20.txt','r')
f[3]=open('E:/cyg/home/Aiurea/workspace/nCompare5w50.txt','r')
f[4]=open('E:/cyg/home/Aiurea/workspace/nCompare5w80.txt','r')

for i in range(5):
    f[i].close()

错误信息是“IndexError: list assignment index out of range”

【问题讨论】:

    标签: python arrays file


    【解决方案1】:

    你需要使用append:

    f.append(open('E:/cyg/home/Aiurea/workspace/nCompare5w5.txt','r'))
    

    在您的代码中,您尝试分配给尚不存在的索引值。

    'append()' 将一个项目添加到列表的末尾。最初,您的列表 f 是空的,但每次您追加它时,都会将该项目添加到列表的末尾,您可以通过访问它的索引号来引用它(或更改它)。

    【讨论】:

    • @Aiurea Adica tot YO - 欢迎来到 SO! f.append(open('path','r')) 就够了
    【解决方案2】:

    您不必重复整个路径/文件名信息:

    import os
    
    path = 'E:/cyg/home/Aiurea/workspace'
    fnames = [ 'nCompare5w{0}.txt'.format(i) for i in (5, 10, 20, 50, 80) ]
    
    f = []
    for fname in fnames:
        with open(os.path.join(path, fname), 'r') as fr:
            f.append(fr.readlines())
    

    另外,with 构造可以让您在最后关闭文件。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-11-11
      • 2014-07-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-06
      • 2018-06-28
      • 2019-11-11
      相关资源
      最近更新 更多