Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to 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, being able to accept file input directly from the command line enhances the flexibility and usability of our program.
Python provides built-in modules such as sys and argparse that make this task straightforward and efficient. In this article, we'll explore different methods 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.
sys.argv
Where:
- sys.argv is a list containing command-line arguments passed to the 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 receive the file path from the command line and read the file ?
import sys
def read_file_from_command_line():
# Check if the filename is provided
if len(sys.argv) < 2:
print("Usage: python script.py <filename>")
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:")
print(content)
except FileNotFoundError:
print(f"Error: File '{filename}' not found.")
except IOError:
print(f"Error: Cannot read file '{filename}'.")
# Call the function
if __name__ == "__main__":
read_file_from_command_line()
Run the script from the command line using:
python script.py data.txt
The output will be:
File Content: This is the content of data.txt
Using argparse
The argparse module is a built-in Python module for parsing command-line arguments. It provides more flexible and user-friendly ways to define and process arguments, automatically generates help messages, and supports both positional and optional arguments.
Basic syntax to create 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:")
print(content)
except FileNotFoundError:
print(f"Error: File '{args.filename}' not found.")
except IOError:
print(f"Error: Cannot read file '{args.filename}'.")
# Call the function
if __name__ == "__main__":
read_file_with_argparse()
Run the script from the command line using:
python script.py data.txt
The output will be:
File Content: This is the content of data.txt
Comparison
| Method | Complexity | Help Messages | Best For |
|---|---|---|---|
sys.argv |
Simple | Manual | Basic scripts |
argparse |
More advanced | Automatic | Professional applications |
Conclusion
Use sys.argv for simple scripts that need basic command-line file input. Use argparse for more robust applications that require better error handling and automatic help generation.
