Hi guys ,

Im new at pythons . Hope you all can help me out here :
Im trying to write a code which prints the elements from every list as a line . so If my lists are :

l1 =
l2 =
l3 =

the first two line of my output file should look like this :

0000002 a 1
0000003 b 2

I tried it in this way but it didnt work :


def listtofile():
l1 =
l2 =
l3 =

test_file = open('test3.txt', 'w')

for i in range(0,8):
s = l1+ '\t' + l2 + '\t' + l3
test_file.write(s)
test_file.readline()
test_file.close()


>>> listtofile()
Traceback (most recent call last):
File "C:\Program Files (x86)\Wing IDE 101 3.2\src\debug\tserver\_sandbox.py", line 1, in <module>
# Used internally for debug sandbox under external interpreter
File "C:\Program Files (x86)\Wing IDE 101 3.2\src\debug\tserver\_sandbox.py", line 10, in listtofile
ValueError: I/O operation on closed file
>>>

It's a little hard to tell from your code (no tabs) but I'm guessing from the error that you have the test_file.close() line tabbed in the for loop code.

If you think about how a for loops works, it will execute each line of the body one at a time until the end of the loop is hit, then loop back up and do it again. So if you close the file inside the loop, then after the first iteration the file closes so on the second iteration when it attempts to write to the file it sees the file is not open for writing, thus you get the error you see there.


That is the bug causing your current error. Fixing it will raise a new error but I will leave that one for you to solve.

Good luck!

ok I took the close statement out of the for loop now , but now Im getting another error . Is this the bug you meant previously?:-/


Traceback (most recent call last):
File "C:\Program Files (x86)\Wing IDE 101 3.2\src\debug\tserver\_sandbox.py", line 1, in <module>
# Used internally for debug sandbox under external interpreter
File "C:\Program Files (x86)\Wing IDE 101 3.2\src\debug\tserver\_sandbox.py", line 9, in listtofile
IndexError: list index out of range
>>>

ok I fixed the range now , it should be range(0,7) , but now I getting this error and the datafile is somehow corrupted :


0000002 a 1 (½ p½ i” :
0000003 b 2 0½ P½0008', '0000 0000 (½ l2 =
0000004 c 31','2','3','4','5','6','7']
0000005 d 4st_file = open('test3.txt', 'w')
0000008 e 5r i in range(0,7):
0000009 f 6 l1+ '\t' + l2 + '\t' + l3
0000010 g 7t_file.write(s)

how do i get rid of those unessary characters ?


the error:

Could not convert all characters in c:\Users\Kang\Desktop\Python\workstudy\test3.txt when reading it as a cp1252 encoded file. Replacing unmappable characters with ?'s so saving the file may result in a corrupted file. You may want to re-open the file using another encoding

ok I took the close statement out of the for loop now , but now Im getting another error . Is this the bug you meant previously?:-/


Traceback (most recent call last):
File "C:\Program Files (x86)\Wing IDE 101 3.2\src\debug\tserver\_sandbox.py", line 1, in <module>
# Used internally for debug sandbox under external interpreter
File "C:\Program Files (x86)\Wing IDE 101 3.2\src\debug\tserver\_sandbox.py", line 9, in listtofile
IndexError: list index out of range
>>>

Yes. This is the second error I noticed.

Look at your list index value (i) and notice how it is growing. What ranges does your loop generate? What range of values will your list index allow?

There is a value you generate as a list index that your lists will not allow. This is where your bug is now. Once you devise correct answers to the 2 questions I just posed, you should see the error.

I still cant seem to figure out why there are those extra characters in my output file. What could possbily went wrong?

I still cant seem to figure out why there are those extra characters in my output file. What could possbily went wrong?

Now comes the question of why you try to read lines of a file you have marked for write only.

I would guess that line of code is the source of your troubles.

hi pls put code tags next time dude :)

try this:

def listtofile():
    l1 = ['0000002', '0000003', '0000004', '0000005', '0000008', '0000009', '0000010']
    l2 = ['a','b','c','d','e','f','g']
    l3 = ['1','2','3','4','5','6','7']    
    s = ""

    f = open( "testFile.txt", "w" )
    for i in range( len( l1 ) ):
        s = l1[ i ] + " " + l2[ i ] + " " + l3[ i ] + "\n"
        print s[ :-1 ] #remove new line character.
        f.write( s )
    #close file when done editing.
    f.close()

listtofile()

#output
>>> 
0000002 a 1
0000003 b 2
0000004 c 3
0000005 d 4
0000008 e 5
0000009 f 6
0000010 g 7
>>>
#the file also contains all of these lines

first open the file for writing, then write each string separately in the for loop and you can also print it if you want to, and at the end close the file. hope this helps :)

Edited 7 Years Ago by masterofpuppets: n/a

def writeListsToFile(filename, l1, l2, l3, separator='\t'):
  assert len(l1) == len(l2) == len(l3)
  output = '\n'.join(map(lambda *items: separator.join(items), l1, l2, l3))
  file(filename, 'wt').write(output)

Edited 7 Years Ago by pythopian: n/a

Yes it is working now , thanks all for the great replies ! ,
I guess for some reason using the tab seperator '\t' would cause the file to be corrupted .

hey I was wondering , if there is way to do it if some lists have multiple items :

for eg:

l1 =
l2 =
l3 = [[('1A','1B','1C')],[('2a','3b')],[('4')],[('5')],[('6')],[('7')],[('8A','8B')]]

then the first 4 lines should be like:
0000002 a 1A
0000002 a 1B
0000002 a 1C
0000003 b 2a

I tried to do it with 2 loops , one loop going through each item in list 1 and 2 and second one looping through each item in the tuple of list 3 .
but for some reason I always get tuple out of range .


def listtofile():
l1 =
l2 =
l3 = [[('1A','1B','1C')],[('2a','3b')],[('4')],[('5')],[('6')],[('7')],[('8A','8B')]]

test_file = open('test5.txt', 'w')

for i in range(0,7):
s = l1+ ' ' + l2 + ' '
for a in range((len(l3)+1)):
s +=l3[a] +'\n'

test_file.write(s)
test_file.readline()
print s[ :-1 ]

test_file.close()

listtofile()

This article has been dead for over six months. Start a new discussion instead.