0

I have a list of numbers and need to put them all into a text file on their own line. I can't figure out how to call to each item and print them. I only know how to write strings into a text file.

Would I have to count each item and use the range function somehow? There has to be a better way. I'm pretty stuck with what to start with.

f = open("numbers.txt", "r")
numlist = []
for line in f:
  numlist.extend([n for n in map(float, line.split()) if n > 0])
print numlist
f.close()

g = open("output.txt", "w")
g.write(#writes each item in the list on its own line)
g.close()
Niklas B.
  • 92,950
  • 18
  • 194
  • 224
Rob Blaze
  • 43
  • 1
  • 1
  • 6

2 Answers2

2

Or use string formatting

g = open('output.txt', 'w')
for num in numlist:
    g.write("%f\n" % num)
g.close()

Or you can change them to strings in your list comprehension:

numlist.extend([str(n) for n in map(float, line.split()) if n > 0])
Collin Green
  • 2,146
  • 14
  • 12
  • There's one quote too much. That extend should better use a genexpr instead of a list comprehension, too. – Niklas B. Mar 21 '12 at 18:12
  • Yeah, I edited the quote out. The list comprehension is from OPs code screenshot. – Collin Green Mar 21 '12 at 18:14
  • 2
    That doesn't mean that it can't be improved (rather to the contrary, it *should* be improved to help OP learn how it's done properly). You don't need to map to `float` first if what you want is to convert back to a string. A simple `numlist.extend(n for n in line.split() if float(n) > 0)` would be sufficient. – Niklas B. Mar 21 '12 at 18:17
  • Ok. I understand for the most part, but the %f is new to me. Mind explaining it a bit? – Rob Blaze Mar 21 '12 at 18:22
  • %f is for floats. http://docs.python.org/library/stdtypes.html#string-formatting-operations – Collin Green Mar 21 '12 at 18:24
2

Since it seems to be homework I'm just going to give some pointing:

  • You can handle multiple files with one with statement, take a look at: Python: open multiple files using “with open”?: (I'll write this one for you)

    with open('numbers.txt') as input_file, open('output.txt', 'w') as output_file:
    
  • Loop line by line of the input_file.

  • strip() and split() the line and loop on it.
  • Check your contintion:

    if float(num) > 0:
    
  • And if pass with your num + '\n'.

Community
  • 1
  • 1
Rik Poggi
  • 28,332
  • 6
  • 65
  • 82
  • This is very helpful. We haven't learned about opening both files like that. But it makes it a lot easier. Thank you!! – Rob Blaze Mar 21 '12 at 18:35