0

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

Balla Botond
  • 55
  • 11

3 Answers3

3

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.

ahmadjanan
  • 298
  • 2
  • 9
0

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.

Sherlock Bourne
  • 490
  • 1
  • 5
  • 10
0

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

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

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