有没有办法检查当前完整代码的长度?
与此类似:
#The file is the current code, not an another
file = open("main.py", "r")
length_in_lines = file.linelength()
length_in_characters = file.chars()
如果您知道解决此问题或修复错误的类似方法,请在代码上感谢您:D
有没有办法检查当前完整代码的长度?
与此类似:
#The file is the current code, not an another
file = open("main.py", "r")
length_in_lines = file.linelength()
length_in_characters = file.chars()
如果您知道解决此问题或修复错误的类似方法,请在代码上感谢您:D
尝试以下操作:
file = open("main.py", "r")
length_in_lines = len(file.readlines())
file.seek(0)
length_in_char = len(file.read())
readlines()
读取列表中文件的所有行。
read()
以字符串形式读取整个文件。
该len()
函数返回参数的长度。
你可以试试这个:
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))
您将首先获得一个包含所有行的列表,并获得列表的长度(即行数),然后您将整个文件作为字符串读取并计算其中的所有字符。
使用下面的代码来读取字符和代码行。
file = open("main.py", "r")
print(len(file.readlines()))
print(len(file.read()))