Queer European MD passionate about IT

lines.py 962 B

123456789101112131415161718192021222324252627282930313233
  1. import os
  2. import sys
  3. def main():
  4. try:
  5. file_name = sys.argv[1]
  6. except IndexError:
  7. print("Provide a file name from command line!")
  8. sys.exit(1)
  9. if len(sys.argv) > 2:
  10. print("Too many command-line arguments")
  11. sys.exit(1)
  12. if not os.path.isfile(file_name): # Or try opening and catch FileNotFoundError
  13. print(f"The file `{file_name}` does not exist!")
  14. sys.exit(1)
  15. if not file_name.endswith('.py'):
  16. print(f"The file `{file_name}` is not a python script (does not end with the proper suffix)!")
  17. sys.exit(1)
  18. line_count = count_lines(file_name)
  19. print(line_count)
  20. def count_lines(file_name: str) -> int:
  21. line_count = 0
  22. with open(file_name, 'r') as file_object:
  23. for line in file_object:
  24. if len(line.strip()) > 0 and not line.strip().startswith('#'):
  25. line_count += 1
  26. return line_count
  27. if __name__ == "__main__":
  28. main()