Write to a File from Command Line using Python



Through the command line, we can easily create dynamic scripts that modify or generate files based on user input. This functionality is useful for generating logs, exporting data, or saving outputs from calculations. The following are the basic steps we need to follow to write data into a file from the command line -

  • Accept the file name and optional data from the command line.
  • Open the specified file in write mode.
  • Write the content to the file.
  • Handle possible errors such as issues with file permissions or invalid inputs.

In this article, we are going to see the different methods that can be used to write data into a file from the command line -

Using sys.argv

The sys.argv list in Python can be used to capture the file name and other data provided via the command line. Following is the syntax of using the sys.argv -

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.

Following is an example of the sys.argv to write data into a file by using the command line -

import sys

def write_to_file():
    if len(sys.argv) < 3:
        print("Usage: python script.py <filename> <data>")
        sys.exit(1)

    filename = sys.argv[1]
    data = sys.argv[2]

    try:
        with open(filename, 'w') as file:
            file.write(data)
            print(f"Data successfully written to {filename}")
    except IOError:
        print(f"Error: Could not write to {filename}")

Here is the command to run the above script from the command line -

python script.py output.txt

Following is the output of the above executed command -

Data successfully written to output.txt

Using argparse

For more complex scenarios, we can use the argparse module. It allows us to define and parse command-line arguments with additional features such as providing default values, displaying help messages, and supporting optional flags. Here is the syntax of argparse, which is used to write the data into a file from the command line using Python -

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.

Following is an example -

import argparse

def write_to_file_with_argparse():
   parser = argparse.ArgumentParser(description="Write content to a specified file.")
   parser.add_argument("filename", help="The name of the file to write to")
   parser.add_argument("data", help="The content to write to the file")
   args = parser.parse_args()

   try:
      with open(args.filename, 'w') as file:
         file.write(args.data)
         print(f"Content written to {args.filename}")
   except IOError:
      print(f"Error: Unable to write to {args.filename}")

The following is the command to run the above script to write the data into a file from command line -

python script.py output.txt

Here is the output of the above strong -

Content written to output.txt

Below are the additional Features of argparse -

  • Help Messages: Automatically generated help messages with -h or --help.
  • Optional Arguments: Supports flags and optional parameters by making it more flexible.

Key Considerations

We need to consider a few points while writing the data into a file using the command line in Python. They are -

  • Write Mode: The 'w' mode opens the file for writing or overwriting it, if it already exists. We can use 'a' to append to the file instead.
  • Error Handling: We should always include error handling techniques, such as try...except, to deal with issues like file not found or insufficient permissions.
  • Argument Validation: We should ensure that the user provides valid arguments, e.g., check if a filename is provided.
Updated on: 2025-04-17T18:26:56+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements