-1

Possible Duplicate:
Joining List has integer values with python

I'm having a syntax problem with for loops and list in python. I'm trying to export a list of numbers that's exported to a text file that's space delimited.

Example: what should be in the text file 0 5 10 15 20

The code I'm using is below, any ideas how to fix this.

f = open("test.txt", "w")
mylist=[]
for i in range(0,20+1, 5):      
    mylist.append(i)
    f.writelines(mylist)

f.close()
Community
  • 1
  • 1
Rick T
  • 3,349
  • 10
  • 54
  • 119

4 Answers4

5

If you want to use range() to generate your list of numbers, then you can use this:

mylist = map(str, range(0, 20 + 1, 5))
with open("test.txt", "w") as f:
    f.writelines(' '.join(mylist))

map(str, iterable) will apply str() on all elements in this iterable object.

with is used to wrap the execution of a block with methods defined by a context manager This allows common try...except...finally usage patterns to be encapsulated for convenient reuse. What it does in this case is it will always close f. It is a good practice to use it instead of manually call f.close().

K Z
  • 29,661
  • 8
  • 73
  • 78
  • @RickT Glad to help :) You can also to read on `with` and `map` in the linked documents, as they are very useful common functions to use. – K Z Oct 09 '12 at 07:08
4

Try this:

mylist = range(0,20+1,5)
f = open("test.txt", "w")
f.writelines(' '.join(map(str, mylist)))
f.close()
Alex
  • 41,580
  • 88
  • 260
  • 469
1

You have to convert your list of integers into a list on strings map() to make it joinable.

mylist = range(0,20+1,5)
f = open("test.txt", "w")
f.writelines(' '.join(map(str, mylist)))
f.close()

see also Joining List has Integer values with python

Community
  • 1
  • 1
0
>>> with open('test.txt', 'w') as f:
...     f.write(' '.join((str(n) for n in xrange(0, 21, 5))))
Demian Brecht
  • 21,135
  • 5
  • 42
  • 46