G
G
Govnokodddd2020-08-07 10:12:25
Python
Govnokodddd, 2020-08-07 10:12:25

How to fix this bug?

There is a code:

if __name__ == "__main__":
  path = input('Введите имя файла:')
  a = open(path)
  act = input('Какое действие хотите выполнить с файлом? \n 1. Подсчитать кол-во строк \n 2. Подсчитать кол-во символов в файле \n 3. 1 + 2: ')
  
def countLines(name):
  count = 0
  for l in name.readlines():
    count += 1
  return count
def countChars(name):
  b = len(name.read())
  return b
def test(name):
  print(countLines(name))
  print(countChars(name))
  return "Done"
  
if __name__ == "__main__":
  if act == "1":
    print(countLines(a))
  elif act == "2":
    print(countChars(a))
  elif act == "3":
    print(test(a))
  else:
    print("Ошибка")


3 action works only half way, performing the first function. How to fix this defect?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey Tikhonov, 2020-08-07
@Govnokodddd

When you have counted the lines in a file, you have read it to the end. After that, the call to read() will return EOF, i.e. in fact, no more characters can be read. To read the file again, you need to call seek(0) (well, or write another method that counts both lines and characters at the same time).

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question