Python File Input / Output :

File Handling :

File handling is an important part of any web application. Python has several functions for creating, reading, updating, and deleting files.

The key function for working with files in Python is the open() function. The open() function takes two parameters; filename, and mode. There are four different methods (modes) for opening a file:

  • " r " - Read - Default value. Opens a file for reading, error if the file does not exist
  • " a " - Append - Opens a file for appending, creates the file if it does not exist
  • " w " - Write - Opens a file for writing, creates the file if it does not exist
  • " x " - Create - Creates the specified file, returns an error if the file exists

In addition you can specify if the file should be handled as binary or text mode :

  • " t " - Text - Default value. Text mode
  • " b " - Binary - Binary mode (e.g. images)

Syntax :

To open a file for reading it is enough to specify the name of the file:f = open("demo_file.txt") and f = open("demo_file.txt", "rt")

Because " r " for read, and " t " for text are the default values, you do not need to specify them.

Note : Make sure the file exists, or else you will get an error.


Python File Open (read a file) :

To open the file, use the built-in open() function. The open() function returns a file object, which has a read() method for reading the content of the file:

demo_file.txt

Hello! Welcome to techbaz.org
This messege from demo_file.txt and this is testing purposes.

my_file.py

  1. f = open("demo_file.txt", "r")
  2. print(f.read())
  3. input()

Output :

python file open

Different ways to Read a File :

You can a read a file different ways here we discus some basic ways so let's start:

Example 1 :

  1. # we not open a file again and again
  2. f = open("demo_file.txt", "r")
  3. print(f.read(6)) #Return the 6 first characters of the file
  4. print(f.readline()) #You can return one line by using the readline() method
  5. print(f.readline()) #By calling readline() two times, you can read the two first lines
  6. input()

Output 1 :

python file open different ways

Example 2 :

By looping through the lines of the file, you can read the whole file, line by line :

  1. # Loop through the file line by line
  2. f = open("demo_file.txt", "r")
  3. for x in f:
  4. print(x)
  5. print("\n[ for loop, help us for reading a file :) ]")
  6. input()

Output 2 :

python file open use for loop


Python File Write (create a file ) :

To write to an existing file, you must add a parameter to the open() function : " a " " w "

Example 1 :

my_file.py

  1. #Append content to the file:
  2. f = open("demo_file.txt", "a")
  3. f.write("\nNow the file has one more line!")
  4. f.close() # the close() method to close a file.
  5. #Now read the "demo_file.txt" file:
  6. f = open("demo_file.txt", "r")
  7. print("'demo_file.txt' File content :")
  8. print(f.read())
  9. f.close()
  10. #Overwrite the content:
  11. f = open("demo_file.txt", "w")
  12. f.write("Overwrite the existing content!")
  13. f.close()
  14. #Now read the "demo_file.txt" file:
  15. f = open("demo_file.txt", "r")
  16. print("\n\n\n'demo_file.txt' File content after overwrite :")
  17. print(f.read())
  18. f.close()
  19. input()

Output 1 :

python file open use for loop

Note : the " w " method will overwrite the entire file.

Example 2 :

To create a new file in Python, use the open() method, with one of the following parameters:

  • " x " - Create - will create a file, returns an error if the file exist
  • " a " - Append - will create a file if the specified file does not exist
  • " w " - Write - will create a file if the specified file does not exist

my_file.py

  1. #Create a file called "new_file.txt"
  2. f = open("new_file.txt", "x")
  3. f.write("New file created.")
  4. f.close()
  5. #Now read the "new_file.txt" file:
  6. f = open("new_file.txt", "r")
  7. print("'new_file.txt' File content :")
  8. print(f.read())
  9. f.close()
  10. #Create a new file if it does not exist:
  11. f = open("new_file2.txt", "w")
  12. f.write("Another New file created.")
  13. f.close()
  14. #Now read the "new_file2.txt" file:
  15. f = open("new_file2.txt", "r")
  16. print("\n\n\n'new_file2.txt' File content :")
  17. print(f.read())
  18. f.close()
  19. input()

Output 2 :

python new file creation

Note : Python automatically closes a file when the reference object of a file is reassigned to another file. It is a good practice to use the close() method to close a file.


Python Delete File (delete a file) :

To delete a file, you must import the OS module, and run its os.remove() function.

Example 1 :

  1. import os
  2. os.remove("new_file.txt")
  3. print("'new_file.txt' delete successfully!")
  4. input()

Output 1 :

python delete a file

Example 2 :

To avoid getting an error, you might want to check if the file exist before you try to delete it.

  1. import os
  2. if os.path.exists("demo_file.txt"):
  3. os.remove("demo_file.txt")
  4. print("'demo_file' delete successfully!")
  5. else:
  6. print("The file does not exist!")
  7. input()

Output 2 :

python delete a file (if else statement)

Computer Science Engineering

Special Notes

It's a special area where you can find special questions and answers for CSE students or IT professionals. Also, In this section, we try to explain a topic in a very deep way.

CSE Notes