Python Program To Create And Write To A Text File

Python Program To Create And Write To A Text File

Published on October 21 2021

In this tutorial, you will learn how to create a text file, write some data and save the file on a local machine using python.

Methods

Python provides inbuilt function for creating, writing and reading files, so there is no need to import external libraries. We'll see some basics.

  1. Open method.
  2. With and Open method

Refer Python Doc

Modes

Modes Description
'r' open for reading (default)
'w' open for writing, truncating the file first
'x' open for exclusive creation, failing if the file already exists
'a' open for writing, appending to the end of file if it exists
'b' binary mode
't' text mode (default)
'+' open for updating (reading and writing)

 

 

 

 

Code Explanation

  1. First step is to create a file. To create a new file in python, we will use the Python open method.
    file = open("myfile.txt","w")

    The open method accepts many arguments, but most of the time you will only use two.

    1. File Name
      • Specify the full path of the file or if you want to create file in the same directory, just write the file name.
    2. Mode
      • Python provides multiple modes (refer above table). In this example, the file has not been created yet, so will use write (W) mode.
  2. The write method to enter data into the file.
    file.write("data inside file.")
  3. It is always recommended to close the file object using the close method
    file.close()
  4. Run the program.
  5. “myfile.txt” file will be created with some data.
  6. Using the above method we have to specifically close the file object. To let Python close file instances automatically, we can use the with method.
    with open("myfile.txt","w") as file:
        file.write("data inside file.")
    We don't have to write a close method and Python will automatically close the file instance.
  7. If the filename name or the file path is incorrect, you will get a file not found error.
  8. To avoid such issues, it is always recommended or as a best practice to write file operation using try-catch block.
    try:
        file=open("myfile.txt","r")
    except IOError:
        print("Error : Filename or file path is incorrect.")
    finally:
        print("exiting...")

Source Code

# method - 1
file = open("myfile.txt","w")
file.write("data inside file.")
file.close()

# method - 2
with open("myfile.txt","w") as file:
    file.write("data inside file.")

# method - 3
try:
    file=open("myfile.txt","r")
except IOError:
    print("Error : Filename or file path is incorrect.")
finally:
    print("exiting...")

Output

"myfile.txt"
data inside file.