

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to read a file from command line using Python?
In order to read a file form command line using Python, the script you want to use for it needs to accept a CLI argument. For example, say you want to write a cat command in python(a command that dumps all file content on the terminal). In order to do that, you could simply write a program:
import sys with open(sys.argv[1], 'r') as f: contents = f.read() print contents
If you save this file as cat.py and run it using:
$ python cat.py my_file.txt
This will take the my_file.txt and pass it to cat.py as a CLI argument in variable argv[1](second command line argument) which we can use to get the file and its contents.
- Related Questions & Answers
- How to write into a file from command line using Python?
- How to read an entire line from a text file using Python?
- How to read complete text file line by line using Python?
- Read file line by line using C++
- Read last line from file in PHP
- How to read data from a file using FileInputStream?
- How to run Python functions from command line?
- How to call Python module from command line?
- How to read a number of characters from a text file using Python?
- How to read only the first line of a file with Python?
- How to Pretty print Python dictionary from command line?
- How to read data from *.CSV file using JavaScript?
- Read Data from a Text File using C++
- How to read integers from a file using BufferedReader in Java?
- How to run TestNG from command line?
Advertisements