Aiurea Adica tot YO
Aiurea Adica tot YO

Reputation: 327

how to store the contents of files in arrays using python?

i have 5 text files that need to be stored in arrays. i've tried it like this.

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()

the error message is "IndexError: list assignment index out of range"

Upvotes: 2

Views: 1332

Answers (2)

eumiro
eumiro

Reputation: 213125

You don't have to repeat the whole path/filename information:

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())

Also the with construct spares you the file closing at the end.

Upvotes: 2

fraxel
fraxel

Reputation: 35319

You need to use append:

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

In your code you are trying to assign to index values that do not exist yet.

'append()' adds an item to the end of a list. Initially your list, f is empty, but every time you append it'll add that item to the end of the list, and you can reference it (or change it) by accessing with its index number.

Upvotes: 3

Related Questions