E-Books

πŸ—‚οΈ File Handling in Python

File handling is an essential part of programming that allows you to read, write, update, and delete files from within your Python programs.

πŸ—‚οΈ Types of Files in PythonHeading

Python works with two major types of files: 1. Text Files and 2. Binary Files

Feature Text File Binary File
Format Human-readable Machine-readable (0s and 1s)
Data Type Textual data Multimedia, image, audio, video etc.
File Modes "r", "w", "a", etc. "rb", "wb", "ab", etc.
Encoding Usually uses UTF-8 No encoding used
Examples .txt, .csv, .py .jpg, .mp3, .exe
Readable Yes, by humans No, only by programs

πŸ“‚ File Opening Modes in Python

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:

Mode Name Description
"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

Mode Name Description
"t" Text Default value. Text mode
"b" Binary Binary mode (e.g. images)

πŸ—‚οΈ Opening and Reading Files in Python

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:

Syntax: file_object = open("filename.txt", "mode")


  # Open and read a file
  file = open("example.txt", "r")  # Open in read mode
  content = file.read()            # Read full content
  print(content)
            

πŸ”’ Closing Files in Python

After performing read/write operations, it’s important to close the file to free up system resources.

Note: You should always close your files. In some cases, due to buffering, changes made to a file may not show until you close the file.


  # Using close()
  file = open("example.txt", "r")
  content = file.read()
  print(content)
  file.close() # Always close the file

  # Recommended: Using with (Context Manager)
  with open("example.txt", "r") as file:
      content = file.read()
      print(content)
  # File is automatically closed after this block
            

πŸ“ Writing Files in Python

In Python, you can create or modify a file using the write() methods. The file must be opened in a write mode:

"a" - Append - will append to the end of the file

"w" - Write - will overwrite any existing content


  content = "Hello Students!\nWelcome to Python File Handling."
              
  file = open("sample.txt", "w")
  file.write(content)
  file.close()
            

πŸ—‚οΈ Python File Methods and Property

Paragraph

Function Description Example
open() Opens a file and returns a file object file = open("file.txt", "r")
read(size) Reads specified number of characters file.read(10)
readline() Reads one line from the file file.readline()
readlines() Reads all lines and returns a list file.readlines()
write() Writes a string to the file file.write("Hello")
writelines() Writes list of strings to the file file.writelines(["Hi", "Hello"])
close() Closes the file file.close()
seek() Moves the pointer to a specific byte file.seek(0)
tell() Returns current file pointer position file.tell()
Property Description Example
name Returns file name file.name
mode Returns access mode file.mode
closed Returns True if file is closed file.closed

πŸ—‚οΈ open() File Methods in Python

The open() function is used to open a file and returns a file object. It is the starting point for any file operations in Python.

Syntax: file_object = open("filename", "mode")


  file = open("example.txt", "r")
            

πŸ—‚οΈ read() Methods in Python

The read() function reads the content of the file. You can read the entire file or a specific number of characters.

Syntax: file.read(size)


  # Read Entire File
  file = open("example.txt", "r")
  content = file.read()
  print(content)
  file.close()

  # Read Specific Number of Characters
  file = open("example.txt", "r")
  content = file.read(6)
  print(content)
  file.close()
            

πŸ—‚οΈ readline() Methods in Python

The readline() function reads one line from the file at a time. Each call to readline() reads the next line.

Syntax: file.readline()


  file = open("example.txt", "r")
  line1 = file.readline()
  line2 = file.readline()
  print("Line 1:", line1)
  print("Line 2:", line2)
  file.close()
            

πŸ—‚οΈ readlines() Methods in Python

The readlines() function reads all lines of a file and returns them as a list of strings. Each line becomes one element of the list.

Syntax: file.readlines()


  file = open("example.txt", "r")
  lines = file.readlines()
  print(lines)
  file.close()
            

πŸ—‚οΈ write() Methods in Python

The write() function is used to write a string to a file. If the file is opened in write ("w") or append ("a") mode, it will insert the content into the file.

Syntax: file.write(string)


  file = open("example.txt", "w")
  file.write("Python is fun!\n")
  file.write("Let's learn file handling.")
  file.close()
            

πŸ—‚οΈ writelines() Methods in Python

The writelines() function writes a list of strings to the file. Unlike write(), it can add multiple lines at once.

Syntax: file.writelines(list_of_strings)


  lines = ["Hello Students!\n", "Welcome to Python File Handling.\n", "Enjoy Learning!\n"]
  file = open("example.txt", "w")
  file.writelines(lines)
  file.close()
            

πŸ—‚οΈ seek() Methods in Python

The seek() function is used to move the file cursor (pointer) to a specific position in the file. It helps you control where to read or write from.

Syntax: file.seek(offset, from_what)

offset: Number of bytes to move the cursor.

from_what: optional Reference position. Default is 0.

0 – Beginning of the file (default)

1 – Current file position

2 – End of the file


  file = open("example.txt", "r")
  file.seek(7)  # Move to the 8th character (index 7)
  content = file.read()
  print(content)
  file.close()
            

πŸ—‚οΈ tell() Methods in Python

The tell() function returns the current position of the file cursor (in bytes) from the beginning of the file.

Syntax: file.tell()


  file = open("example.txt", "r")
  print("Initial position:", file.tell())
  file.read(5)
  print("Position after reading 5 characters:", file.tell())
  file.close()
            

πŸ—‚οΈ close() Methods in Python

The close() function is used to close an open file. It is important to free up system resources and ensure that all data is properly written to disk.

Syntax: file.close()


  file = open("example.txt", "w")
  file.write("Closing the file after writing.")
  file.close()
            

πŸ—‚οΈ Working with Binary Files in Python

To work with binary files, use a b in the mode and using pickle Module to read and write Binary File.

βœ… Write Data to a Binary File

Syntax: pickle.dump(object , file_handler) - used to write any object to the binary file.


              import pickle
              
              fruits = ["Apple", "Banana", "Mango", "Orange"]
              
              file = open("fruits.dat", "wb")  # open in binary write mode
              pickle.dump(fruits, file)        # serialize and save
              file.close()
            


βœ… Read Data from the Binary File

Syntax: Object = pickle.load(file_handler) - used to read object from the binary file.


  import pickle

  file = open("fruits.dat", "rb")  # open in binary read mode
  fruits = pickle.load(file)       # deserialize
  file.close()

  print("Fruits List:", fruits)
            

πŸ—‚οΈ Command Line Arguments in Python

Command Line Arguments allow you to pass values to your Python script when it is executed from the terminal or command prompt.

Feature Description Example
Module sys is used to fetch command-line arguments import sys
Argument List sys.argv returns arguments as a list of strings sys.argv[1] gives 1st argument
Script Name sys.argv[0] is always the script name script.py
Number of Arguments Use len(sys.argv) to count arguments len(sys.argv)
Type Conversion Arguments are strings, convert if needed int(sys.argv[1])


  import sys
              
  # total arguments
  n = len(sys.argv)
  print("Total arguments passed:", n)
              
  # Arguments passed
  print("\nName of Python script:", sys.argv[0])
              
  print("\nArguments passed:", end = " ")
  for i in range(1, n):
      print(sys.argv[i], end = " ")
              
  # Addition of numbers
  Sum = 0
  # Using argparse module
  for i in range(1, n):
      Sum += int(sys.argv[i])
              
  print("\n\nResult:", Sum)
            

Previous Next