-2

I'm trying to get a python script working that will take an .txt file with number inputs

10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26

and turn it into

Hello 10 and 11 and 12 and 13....

and after x numbers it should start again like

Hello 10 and 11 and 12 and 13

Hello 14 and 15 and 16 and 17

Hello 18 ....

what ive got is this

def idcommands(contentsplit):
    command = ' and '.join(contentsplit)

    textfile = open('command.txt', 'w')
    textfile.write("Hello " +command)
    textfile.close()

def main():
    file = open("ids.txt", "r")

    content = file.read()
    contentsplit = content.split(' ')

    file.close()

    idcommands(contentsplit)

So it will do it all in one line but I don't know how to split after x numbers.

Nimantha
  • 6,405
  • 6
  • 28
  • 69
Tyres
  • 11
  • 2

1 Answers1

0

It's not clear if you want a separate file for each line or one file for them all.

This code will create one file.

def idcommands(contentsplit, n = 4):
    commands = ['Hello ' + ' and '.join(contentsplit[idx:idx+n]) for idx in range(0, len(contentsplit), n)]
    with open('command.txt', 'w') as textfile:
        textfile.write('\n'.join(commands))
        
def main():
    file = open("ids.txt", "r")

    content = file.read()
    contentsplit = content.split(' ')

    file.close()

    idcommands(contentsplit, 2)

main()     
norie
  • 9,609
  • 2
  • 11
  • 18