2

My task is to: "Write a program that reads and prints out all lines that start with a given letter. The file path and starting letter will be given as command-line arguments. You may assume that all command-line arguments will be valid"

e.g.

$ cat cats.txt
calico
siamese
ginger
cute, cuddly

$ python3 filter.py cats.txt c
calico
cute, cuddly

$ python3 filter.py cats.txt g
ginger

My code right now looks like:

import sys
with open("cats.txt", "r") as f:
   a = f.readlines()
   word_no = 0
   l = len(a) - 1
   while word_no <= l:
       if (a[word_no][0]) == sys.argv[1]:
           print (a[word_no])
       word_no += 1

However, I'm not passing the test cases as my code shows up with no output, even though it works with the sample textfile? enter image description here

3
  • 4
    You've hardcoded the path of the file while it's given as argument Commented Jun 7, 2020 at 10:55
  • 1
    would probably be more ideomatic to do for line in f: if f.startswith(sys.argv[2]): print(line.strip()) - strip to avoid \n\n Commented Jun 7, 2020 at 11:01
  • 1
    Also, it's sys.argv[2], sys.argv[0] is 'filter.py' Commented Jun 7, 2020 at 11:02

1 Answer 1

3

There seems to be a few mistakes in your code - hard-coded file path, incorrect index of sys.argv and printing line with \n. Corrected code:

import sys
with open(sys.argv[1], "r") as f:
   a = f.readlines()
   word_no = 0
   l = len(a) - 1
   while word_no <= l:
       if (a[word_no][0]) == sys.argv[2]:
           print (a[word_no].strip())
       word_no += 1

Also, a better way to write this code would be:

import sys
with open(sys.argv[1], "r") as f:
    for line in f:
        if line[0] == sys.argv[2]:
            print(line.strip())
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.