简体   繁体   中英

Creating CAT program in Python

I am extremely new to programming and I am taking classes at the moment. I'm currently using Cygwin to enable UNIX terminal environment to run Python programs. I need to make a similar program with the UNIX utility cat.

What we usually do on the terminal would be: $cat fileName.txt

Now what I am trying to achieve is to make a cat program in Python: $python3 cat.py filename1.txt filename2.txt...

I have succeeded to create that, but I am confused as how to implement printing the line number from the external files by implementing -n .

How do you run the code $cat -n filename.txt as python3 cat.py -n filename.txt ?

My program looks like this:

#!/usr/bin/env python3
import sys
numberOfArgs = len(sys.argv)
if numberOfArgs <2:
    sys.stderr.write('Usage: %s inputFile\n' % sys.argv[0])
    sys.exit(1)

for fileName in sys.argv[1:]:
    try:
        fh = open(fileName,'r')
    except:
        sys.stderr.write('cannot open input file %s\n' % fileName[1])
        sys.exit(2)
    for line in fh.readlines():
        print(line, end'')
    fh.close()

actually, your code should work as you wish, the only problem I see is in the print line, you have a typo

print(line, end='')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM