-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathLines of Code
More file actions
38 lines (31 loc) · 946 Bytes
/
Lines of Code
File metadata and controls
38 lines (31 loc) · 946 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
# lines.py
import sys
import os
def main():
# Check for exactly one command-line argument
if len(sys.argv) != 2:
sys.exit("Usage: python lines.py filename.py")
filename = sys.argv[1]
# Check file extension
if not filename.endswith(".py"):
sys.exit("Not a Python file")
# Check if file exists
if not os.path.isfile(filename):
sys.exit("File does not exist")
# Count lines of code
try:
with open(filename, "r") as file:
lines = file.readlines()
count = 0
for line in lines:
stripped = line.strip()
if stripped == "":
continue # Blank line
if stripped.startswith("#"):
continue # Comment line
count += 1
print(count)
except FileNotFoundError:
sys.exit("File not found")
if __name__ == "__main__":
main()