2

from this post, I've been using the following code to write a list/array to a file:

with open ("newhosts.txt",'w') as thefile:
    for item in hostnameIP:
      thefile.write("%s\n" % item)

where hostnameIP is:

[['localhost', '::1'], ['localhost', '::1'], ['localhost', '::1']]

In the file, I get the output:

['localhost', '::1']
['localhost', '::1']
['localhost', '::1']

when I need to to say

localhost, ::1
localhost, ::1
localhost, ::1

What would be the best way to do this?

Community
  • 1
  • 1
DonD
  • 339
  • 3
  • 17

5 Answers5

3

Use:

with open ("newhosts.txt", "w") as thefile:
    for item in hostnameIP:
        thefile.write("%s\n" % ", ".join(item))

This way each part of item will be printed with an ", " as seperator.

But if you want to make the code even shorter, you can also join each item with a newline:

with open ("newhosts.txt", "w") as thefile:
    thefile.write("\n".join(map(", ".join, hostnameIP)))
JuniorCompressor
  • 19,631
  • 4
  • 30
  • 57
3
with open ("newhosts.txt",'w') as thefile:
    for item in hostnameIP:
      thefile.write("%s, %s\n" % (item[0], item[1]))
ProfOak
  • 541
  • 4
  • 10
2

I would use the csv module simply calling writerows on your list of lists:

import csv
lines = [['localhost', '::1'], ['localhost', '::1'], ['localhost', '::1']]
with open ("newhosts.txt",'w') as f:
    wr = csv.writer(f)
    wr.writerows(lines)

Output:

localhost,::1
localhost,::1
localhost,::1
Padraic Cunningham
  • 176,452
  • 29
  • 245
  • 321
2

From what I can see you have a list with lists as elements. This is why you get the result that you get. Try the following code (see the minor change on the third line) and you will get the wanted result.

with open ("newhosts.txt",'w') as thefile:
    for item in hostnameIP:
      thefile.write("%s\n" % ', '.join(item))
1

You are currently printing string representations of the lists to the file. Since you are only interested in the lists' items, you can use str.format and argument unpacking to extract them:

thefile.write("{}, {}\n".format(*item))