Python Write To File Example

The code below shows how to write to a file using Python. The textfile.txt will be created and the data written as shown in output below.

#
# Python Write To File
#

def main():  
  # Open a file for writing and create it if it doesn't exist
  f = open("textfile.txt", "w+")

  # write some lines of data to the file
  for i in range(15):
    f.write("This is a line " + str(i) + "\r\n")
  
  # close the file when done
  f.close()
  
    
if __name__ == "__main__":
  main()



------------------------------------------------------
Contents of textfile.txt
This is a line 0

This is a line 1

This is a line 2

This is a line 3

This is a line 4

This is a line 5

This is a line 6

This is a line 7

This is a line 8

This is a line 9

This is a line 10

This is a line 11

This is a line 12

This is a line 13

This is a line 14

Comments

Popular posts from this blog

How to write to a file in Kotlin

Python Tkinter example