I have written the same program (open text file and display contents) in C and C++. Now am doing the same in Python (on a Linux machine).
In the C programs I used the code:
if (argc != 2) {     /* exit program */ }   Question: What is used in Python to check the number of arguments
#!/usr/bin/python import sys try:     in_file = open(sys.argv[1], "r") except:     sys.exit("ERROR. Did you make a mistake in the spelling") text = in_file.read() print text in_file.close()   Current output:
./python names.txt = Displays text file (correct) ./python nam = error message: stated from the sys.ext line (correct) ./python = error message: stated from the sys.ext line (wrong: want it to be a separate error message stating *no file name input*) 
                argv is a list in Python that contains all the command-line arguments passed to the script. It is essential in Python while working with Command Line arguments.
IDLE now has a GUI way to add arguments to sys. argv! Under the 'Run' menu header select 'Run... Customized' or just Shift+F5... A dialog will appear and that's it!
In python a list knows its length, so you can just do len(sys.argv) to get the number of elements in argv.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With