0

I have txt file with names which look like that:

Hans
Anna
Vladimir
Michael
Ed
Susan
Janice
Jo

I want to print the sum of all the names length:

with open(r"C:\people_names.txt", "r") as name_file:
    sum_names = (len(x) for x in name_file)
print(sum(sum_names))

The problem is that there is "\n" after every name which count as a letter and the last name dont have "\n",

Thats why I cant do len(x)-1

Will be glad for any suggestions how to do the sum :)

Yevhen Kuzmovych
  • 10,940
  • 7
  • 28
  • 48

3 Answers3

2

I wouldn't recommend using readlines() if the file is too big.
You can use rstrip to remove the \n from the end of each line.

with open(r"C:\people_names.txt", "r") as name_file:
    sum_names = [len(x.rstrip('\n')) for x in name_file]
print(sum(sum_names))
Eliran Turgeman
  • 1,526
  • 2
  • 16
  • 34
1
with open(r"C:\people_names.txt", "r") as name_file:
    data = name_file.read()  

total_characters = len(data) - data.count("\n")
print(total_characters)
ckunder
  • 1,920
  • 1
  • 10
  • 10
0

Read each line from the file :

with open(r"C:\people_names.txt", "r") as name_file:
    name_file = name_file.readlines()
sum_names = [len(x.strip()) for x in name_file]
print(sum(sum_names))

name_file.readlines() returns a list of lines, and these lines are identified by the newline character. That will take care of your issue. An alternative solution will be to use splitlines() :

with open(r"hello.txt", "r") as name_file:
    name_file = name_file.read().splitlines()
sum_names = [len(x) for x in name_file]
print(sum(sum_names))
Roshin Raphel
  • 2,612
  • 4
  • 22
  • 40
  • 1
    Thank you very much! so I dont have to do `name_file = name_file.readlines()` if I use the `len(x.strip()` method –  Jul 20 '20 at 15:33
  • @Ileh then you will have to use name_file = name_file.read() since `with` automatically closes the file handler making it not accessible for the next line – Roshin Raphel Jul 20 '20 at 15:51