0

Currently i have a list of list containing:

lst = [[1,2],[5,4],[10,9]]

and I'm trying to write the output in the form of a text file where it is formatted

1      2
5      4
10     9

I tried:

newfile = open("output_file.txt","w")
for i in range(len(lst)):
    newfile.write(i)
newfile.close()

but I'm getting the error:

TypeError: write() argument must be str, not list

would appreciate some help on this.

2
  • 2
    newfile.write(str(i)) Commented Sep 21, 2018 at 5:19
  • your i is just a index. You need to do lst[i] or run loop over lst (like for l in lst) Commented Sep 21, 2018 at 5:20

5 Answers 5

1

You should change your int values to str and add newline char end of it as below :

lst = [[1,2],[5,4],[10,9]]

newfile = open("output_file.txt","w")
for i in lst:
    newfile.write(str(i[0]) + ' ' + str(i[1]) + '\n')
newfile.close()

output file is :

1 2
5 4
10 9
Sign up to request clarification or add additional context in comments.

Comments

1

You can use a format string instead:

lst = [[1,2],[5,4],[10,9]]
with open("output_file.txt","w") as newfile:
    for i in lst:
        newfile.write('{:<7}{}\n'.format(*i))

Comments

0

you can use numpy module to write into text file like below.

import numpy as np
lst = [[1,2],[5,4],[10,9]]
np.savetxt('output_file.txt',lst,fmt='%d')

Thanks

Comments

0

Write it with a formatted string

with open('output.txt', 'w') as f:
    for i in lst:
        f.write('{}\t{}\n'.format(i[0], i[1]))
(xenial)vash@localhost:~/python/stack_overflow/sept$ cat output.txt
1     2
5     4
10    9

Comments

-1

You are getting the error because you are directly printing the list elements, perhaps the write method of the file need the parameter to be the string and you're passing directly the list elements. Do a thing explicitly convert the items of the list to the string and print.

 newfile = open("output_file.txt","w")
 for i in range(len(lst)):
    newfile.write(str(i))
 newfile.close()

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.