How can I check the length of the python code?

215 views Asked by At

Is there a method to check the length of the CURRENT full code?

Similar to this:

#The file is the current code, not an another
file = open("main.py", "r")
length_in_lines = file.linelength()
length_in_characters = file.chars()

If you know a similar method to solve this or fix the errors, on the code thank you :D

3

There are 3 answers

2
ahmadjanan On BEST ANSWER

Try the following:

file = open("main.py", "r")
length_in_lines = len(file.readlines())
file.seek(0)
length_in_char = len(file.read())

readlines() reads all the lines of the file in a list.

read() reads the whole file in a string.

The len() function returns the length of the argument.

0
Sherlock Bourne On

You can try this:

with open('script.py') as file:
    lines = len(file.readlines())
    file.seek(0)
    chars = len(file.read())

print('Number of lines: {}'.format(lines))
print('Number of chars: {}'.format(chars))

You would first get a list with all the lines, and getting the list's length (so, the number of lines), and then you would read the whole file as a string and count all the characters in it.

0
Mohammad Izaan On

Use the code below for reading characters and lines of code.

file = open("main.py", "r")

print(len(file.readlines()))
print(len(file.read()))