I'm new to python. I'm creating 2 arrays file_name(stores name of the files) and path(stores paths of files). Values of path array are assigned inside while loop. But I'm getting the error:
IndexError: list assignment index out of range in Python
I had already wasted several hours on this one, but haven't got the output as I expected. So, can you please let me know where I have made the mess? Any help will be highly appreciated. Thanks in advance.
My Code:
file_name = ['abc','xyz','pqr','mno','def','ghi','rst','uvw','jkl']
path = []
count = 0
while count < 9:
path[count] = "D:\\Work\\"+file_name[count]+".csv"
print (path[count])
count = count + 1
Expected Output:
D:\\Work\\abc.csv
D:\\Work\\xyz.csv
D:\\Work\\pqr.csv
D:\\Work\\mno.csv
D:\\Work\\def.csv
D:\\Work\\ghi.csv
D:\\Work\\rst.csv
D:\\Work\\uvw.csv
D:\\Work\\jkl.csv
You can't access path[count] and assign something to it if path[count] doesn't already exist.
To create a new list, use .append(). You don't need to keep track of a counter at all (it's rarely necessary to do a C-style loop in Python; the pythonic way is to iterate over the elements of a list/tuple/dictionary directly):
file_name = ['abc','xyz','pqr','mno','def','ghi','rst','uvw','jkl']
path = []
for item in file_name:
newpath = "D:\\Work\\" + item + ".csv"
# or better: newpath = r"D:\Work\{}.csv".format(item)
path.append(newpath)
print(newpath)
You are looking for the append method.
file_name = ['abc','xyz','pqr','mno','def','ghi','rst','uvw','jkl']
path = []
count = 0
while count < 9:
path.append("D:\\Work\\"+file_name[count]+".csv")
print (path[count])
count = count + 1
You will get your expected output.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With