Reputation: 92
I want to iterate on the list of files inside a specific folder, and store files names by pairs words or triplets words. I created this code:
for file_name in os.listdir(path):
file_name_aslist = file_name.split()
o = [(file_name_aslist[x], file_name_aslist [x+1]) for x in range(0, len(file_name_aslist ), 2)]
it returns this error:
IndexError: list index out of range
The expression work on single list, but dont want to work inside the loop: for example:
list = ['ra', 'ti', 'kaa', 'esss', 'fm', 'am']
print([(list[x], list[x+1]) for x in range(0, len(list), 2)])
[('ra', 'ti'), ('kaa', 'esss'), ('fm', 'am')]
also, when I try to iterate on triplets , refuse as well
print([(list[x], list[x+1], list[x+2]) for x in range(0, len(list), 3)])
IndexError: list index out of range
Upvotes: 0
Views: 860
Reputation: 17322
you are splitting the names of the files by " " (space) at this line:
file_name_aslist = file_name.split()
you can not be sure that all the files have more than 1 word after splitting
what can you do:
def chunks_n(my_list, n):
for e in range(0, len(my_list), n):
yield my_list[e: e + n]
my_list = ['ra']
print(list(chunks_n(my_list, 2)))
output:
[['ra']]
Upvotes: 1
Reputation: 140
just add a if condition when length of the list is not multiple of 2 , append an extra empty string in the list to make it even. same for triplets. you have to add one or two string.
#donot use split function.
file_name_aslist = os.listdir(path)
if len(file_name_aslist) // 2 == 0 :
o = [(file_name_aslist[x], file_name_aslist [x+1]) for x in range(0,
len(file_name_aslist ), 2)]
else:
file_name_aslist.append("")
o = [(file_name_aslist[x], file_name_aslist [x+1]) for x in range(0, len(file_name_aslist ), 2)]
Upvotes: 1
Reputation: 1724
First thing: in your example using a "single list", list
does not necessarily represent your original file_name_aslist
. If your file names don't contain spaces, file_name_aslist
will be a list with a single element, the file name itself. For these cases, it is very easy to verify why file_name_aslist [x+1]
will throw a IndexError
.
Do you really expect that file_name_aslist
be a list with more than one element? Are you not trying to split by other criteria, like .
(to possibly split by file extension, which is also a bad approach)?
Upvotes: 0