Read a File from Command Line Using Python



Reading files from the command line is a common task in many Python scripts and automation workflows. Whether we're building a simple utility to process text files or developing a complex data analysis tool that being able to accept file input directly from the command line, which enhances the flexibility and usability of our program.

Python provides built-in modules such as sys and argparse that make our task straightforward and efficient. In this article, we are going to see the different methods that are used to read a file from the command line using Python -

Using sys.argv()

In Python, sys.argv is a list provided by the built-in sys module that stores the command-line arguments passed to a script when it is run. Following is the syntax of the function importlib.util.spec_from_file_location() -

sys.argv

Where,

  • sys.argv is a list in Python that contains the command-line arguments passed to a script.
  • sys.argv[0] is the script name.
  • sys.argv[1] is the first argument, typically the file path.

Example

Below is an example that uses sys.argv to dynamically receive the file path from the command line and import the module -

import sys def read_file_from_command_line(): # Check if the filename is provided if len(sys.argv) ") sys.exit(1) # sys.argv[1] holds the filename filename = sys.argv[1] try: with open(filename, 'r') as file: content = file.read() print("File Content:\n", content) except FileNotFoundError: print(f"Error: File '{filename}' not found.") except IOError: print(f"Error: Cannot read file '{filename}'.")

Now, run the script from the command line by using the below command -

> python script.py data.txt

Following is the output of the above code -

File Content:
This is the content of data.txt

Using argparse

In Python, the argparse is a built-in module used to parse command-line arguments. It provides more flexible and user-friendly ways to define and process arguments automatically by generating help messages and supports both positional and optional arguments.

Following is the syntax to create and use an ArgumentParser object -

import argparse parser = argparse.ArgumentParser() parser.add_argument("filename") args = parser.parse_args()

Where,

  • argparse.ArgumentParser() creates a new argument parser object.
  • add_argument("filename") defines a required positional argument named filename.
  • args.filename retrieves the value passed to that argument.

Example

Below is an example that uses argparse to receive the file path from the command line and read the file -

import argparse def read_file_with_argparse(): parser = argparse.ArgumentParser(description="Read a file from command line.") parser.add_argument("filename", help="The path to the file to read") args = parser.parse_args() try: with open(args.filename, 'r') as file: content = file.read() print("File Content:\n", content) except FileNotFoundError: print(f"Error: File '{args.filename}' not found.") except IOError: print(f"Error: Cannot read file '{args.filename}'.")

Now run the above script from the command line by using the below command -

python script.py data.txt

Following is the output of the above code -

File Content:
This is the content of data.txt
Updated on: 2025-04-17T18:24:13+05:30

552 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements