0
votes

I want to create a for loop that creates a list of numbers, 1 to 10, displays them one for each line, adds ":" right next to each one, and then copy all that to a text file. I've tried many things, while loops, for loops, and functions

nums = range(1, 10)
for x in nums:
    print x, ":"

That displays the numbers with a space in between:

1 :  #instead of 1: 
2 :

I tried using range() in a while loop, and as well to copy it like this:

from sys import argv

script, input_file = argv

openfile = open(input_file, 'w')


nums = range(1, 11)
for x in nums:
    print x, ":"
    openfile.write(x) #here throws me an error

Could someone give me an idea of how I should do it?

1

1 Answers

0
votes

I think this is what you are looking for:

nums = range(1, 11)

text_file = open("nums", "w")

for x in nums:
    num = str(x) + ":" + "\n"
    printOnTxt = text_file.write(num)
    
text_file.close()