Click here to Skip to main content
15,920,217 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have a six item list
Python
x

That I need to append to existing csv files: 'tmp'+j+'.txt'

Python
for eachFile in os.listdir(savePath):
    j = eachFile.strip(".tx")
    with open('tmp/'+j+".txt", "a") as myfile:
        for i in (0, len(x)):
            if i < len(x):
                myfile.write(str(x[i]))
            if i == len(x):
                myfile.write(str(x[i])+"/n")

But I receive the following error. I am doing something pretty basic wrong as this code should work. My brain is not working today.
Python
Traceback (most recent call last):
  File "C:/XXXX.py", line 322, in <module>
    myfile.write(str(x[i])+"/n")
IndexError: list index out of range

Should I adjust the length of the loop for i?
Posted
Updated 17-Nov-15 6:15am
v2
Comments
Richard Deeming 17-Nov-15 12:51pm    
Just a guess, since I don't know Python, but doesn't len(x) return the length of the list, not the index of the last item in the list?

1 solution

You should try
Python
for i in (0, len(x)-1):


And even simplify a few
Python
for eachFile in os.listdir(savePath):
    j = eachFile.strip(".tx")
    with open('tmp/'+j+".txt", "a") as myfile:
        for i in (0, len(x)-1):
            myfile.write(str(x[i]))
        myfile.write("/n")
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900