Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
File Reading
#3
sum_ = 0
numbers = 0
for line in lines:
    try:
        sum_ += int(line)
        numbers += 1
    except ValueError:
        pass
I am assuming that list comprehension is not allowed so here is one way to do it. It's readable and clear.

I just have learned something new. Stripping whitespace characters is not necessary to convert a string to an integer. I tried it couple of minutes ago.

>>> int('  \t10 \n')
10
"As they say in Mexico 'dosvidaniya'. That makes two vidaniyas."
https://freedns.afraid.org
Reply


Messages In This Thread
File Reading - by toxicxarrow - May-07-2018, 09:40 AM
RE: File Reading - by ThiefOfTime - May-07-2018, 10:14 AM
RE: File Reading - by wavic - May-07-2018, 10:30 AM
RE: File Reading - by killerrex - May-07-2018, 10:35 AM
RE: File Reading - by toxicxarrow - May-07-2018, 10:57 AM
RE: File Reading - by killerrex - May-07-2018, 01:47 PM
RE: File Reading - by wavic - May-07-2018, 02:02 PM
RE: File Reading - by toxicxarrow - May-07-2018, 03:02 PM
RE: File Reading - by wavic - May-07-2018, 03:08 PM
RE: File Reading - by toxicxarrow - May-07-2018, 04:12 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Excel File reading vanjoe198 1 2,091 Mar-31-2021, 11:53 AM
Last Post: snippsat
  reading from a file looseCannon101 14 5,202 Jul-18-2020, 11:29 AM
Last Post: GOTO10
  Weird problem with reading from file and performing calculations pineapple999 1 3,070 Jul-25-2019, 01:30 AM
Last Post: ichabod801
  Handling IO Error / Reading from file Expel 10 5,026 Jul-18-2019, 01:21 PM
Last Post: snippsat
  Reading an Unconventional CSV file OzSbk 2 3,934 May-17-2019, 12:15 PM
Last Post: MvGulik
  reading text file and writing to an output file precedded by line numbers kannan 7 10,565 Dec-11-2018, 02:19 PM
Last Post: ichabod801
  Reading of structured .mat (matlab) file sumit 2 3,497 May-24-2018, 12:12 PM
Last Post: sumit
  reading all lines from a text file seadoofanatic 2 2,979 Mar-13-2018, 06:05 PM
Last Post: Narsimhachary
  Reading a text file fivestar 7 5,731 Oct-13-2017, 07:25 AM
Last Post: gruntfutuk
  Dictionary + File Reading palmtrees 2 4,949 Nov-15-2016, 05:16 PM
Last Post: Ofnuts

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020