Skip to content

Python program to write the numbers from one to hundred in a text file

Python program to write the numbers from one to hundred in a text file

In this tutorial we will write a Python program to write the numbers from one to hundred in a text file . Before reading further we recommend to read about following articles –

Python program to write the numbers from one to hundred in a text file

Steps:

  • First we will open a text file in write mode .
  • Then using for loop we will print 1 to 100 in the file .
# opening a file in w mode
with open("output.txt","w") as fp:
    # printing 1 to 100 to the file
    for i in range(1,101):
        fp.write(str(i))
        fp.write(" ")
  • In the above code as we have opened the file using with keyword so we don’t need to close the file .
  • Then using range() function and for loop we have printed 1 to 100 in that file .
  • fp.write(" ") line is used to give a space between every two numbers .

Implementing the above code defining a function

def one_to_hundred(filename):
    # opening a file in w mode
    with open(filename,"w") as fp:
        # printing 1 to 100 to the file
        for i in range(1,101):
            fp.write(str(i))
            fp.write(" ")

one_to_hundred("output.txt")       

Thank you for reading this Article . If You enjoy it Please Share the article . If you want to say something Please Comment .

Leave a Reply