Home > Software design >  how can i create this specific text file using python? (details down below)
how can i create this specific text file using python? (details down below)

Time:10-03

I want a text file that has every variation of xxxxx-xxxxx (x is a number) so I want to create a text file that goes 00000-00000 00000-00001 00000-00002 00000-00003 etc... how can I do that with python?

CodePudding user response:

You can do it using a nested loop like this:

pattern = '00000-00000'
stack = []

for i in range(100000):
    for j in range(100000):
        num = pattern[:5-len(str(i))] str(i)   pattern[5]   pattern[6:-len(str(j))] str(j)
        stack.append(num)

***Just don't run this code. It will break your computer.

CodePudding user response:

The trick is to use .zfill(n) if you want to append "n" zeros before some integers. So, if you have i = 1 but you want to print it like 00001, you can you the following code:

print(str(i).zfill(5))

And as to your question, the solution is:

with open("output.txt", "a") as f:

    for i in range(100000):
        for j in range(100000):
            my_str = str(i).zfill(5)   "-"   str(j).zfill(5)   "\n"
            f.write(my_str)

    f.close()

Note: This will take a while to complete.

CodePudding user response:

Try this.

lst = []

s = '0000000000'

for a in range(10000):
    l = list(s   str(a))[-10:]
    l.insert(4,'-')
    lst.append(''.join(l) '\n')


with open('name.txt','w') as file:
    file.writelines(lst)

  • Related