0

Im trying to create a script that will generate numbers 1000-999999 and save to a text document, but when I save the numbers it, all the numbers are pressed together. Is there a way I can insert a line in-between every number?

import os

pause = lambda: os.system('pause')
clear = lambda: os.system('cls')

clear()
f = open('pass.txt', 'w')
print('pass.txt opened')
print()
for n in range(1000, 10000):
    print('printing numbers 1000-1000000 to pass.txt')
    print()
    f.write('\n'.join(str(sum([n]))))
    print('sucsefully printed to pass.txt')
pause()

2 Answers2

0

I am not sure what you are trying to do with sum str(sum([n]))). I think for loop should simply contain

for n in range(1000, 10000):
    f.write(str(n) + '\n')
Rima
  • 1,447
  • 1
  • 6
  • 12
0

A good way to check what is going on is by checking what each part of your code does. So for example,

f.write('\n'.join(str(sum([n]))))

Looks a bit weird. So lets see what it returns, for a couple of values.

>>> '\n'.join(str(sum([10])))
'1\n0'
>>> '\n'.join(str(sum([1])))
'1'
>>> '\n'.join(str(sum([10])))
'1\n0'
>>> '\n'.join(str(sum([100])))
'1\n0\n0'
>>> '\n'.join(str(sum([1000])))
'1\n0\n0\n0'

And as you can see, the results are also a bit weird. And this is probably not what you want to see.

So, how can you fix this?
If you want strings formatted in a certain way, you can use string formatting. for your case, this would be something like

for number in range(1000, 10000):
    formatted_string = f'{number}\n'
    f.write(formatted_string)

Another issue that I wanted to point it is that you are using the open function directly. While this isn't necessarily wrong. It isn't best practice because it makes it easier to not explicitly close the file (as is the case here).

Instead, you want to use the with keyword This stackoverflow post describes that statement much better. What is the python "with" statement designed for?

So combining this all together, you get something like:

with open('pass.txt', 'w') as f:
    for number in range(1000, 10000):
        formatted_string = f'{number}\n'
        f.write(formatted_string)
bobveringa
  • 230
  • 2
  • 12