0

the below code is to iterate through multiple files:

file_in = list() 
filenames = ['C:\\textfile1.txt', 'C:\\textfile2.txt'] 
x = 0 
for i in filenames:
    file_in[x] = open(i,'r') 
    x += 1 

but it did not work, it gave the following error message:

IndexError: list assignment index out of range.

Any idea to solve it ,thanks you

Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
  • 1
    Does this answer your question? [Why does this iterative list-growing code give IndexError: list assignment index out of range?](https://stackoverflow.com/questions/5653533/why-does-this-iterative-list-growing-code-give-indexerror-list-assignment-index) – dibery Jan 24 '20 at 03:42

2 Answers2

0

That is because the list is empty so you can't assign to specific indexes. You should do:

file_in = list() 
filenames = ['C:\\textfile1.txt', 'C:\\textfile2.txt'] 

for i in filenames:
    file_in.append(open(i,'r'))

Or better yet:

filenames = ['C:\\textfile1.txt', 'C:\\textfile2.txt'] 

file_in = [open(i,'r') for i in filenames]

But it would be far better to use with to open the files:

filenames = ['C:\\textfile1.txt', 'C:\\textfile2.txt'] 
for file in filenames:
    with open(file) as f:
        # do something with the file
Tomerikoo
  • 18,379
  • 16
  • 47
  • 61
0

Check this,

with open("file1.txt") as file1, open("file2.txt") as file2: 
    for x, y in zip(file1, sys_file2):
        x = x.strip() 
        y = y.strip()

This is generally how I do.

Saurav Rai
  • 2,171
  • 1
  • 15
  • 29