Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
String handling
#21
(Sep-16-2019, 05:11 AM)perfringo Wrote: EDITED: initial code contained error. Blank lines contain newline at end, so line must be stripped otherwise it will be truthy (contains newline). Therefore row.strip() should be used. Below code is fixed.

............

From screenshot I observe that there is blank line at the end of file. Problem can be easily mitigated by little defensive code - 'check whether line is empty'. Also I suggest to open files using 'with', among other goodies there is no need to close file - Python does it for you.

with open('filename.txt', 'r') as f:
    for row in f:
        if row.strip():
            # the rest of code

Oh wow I did not know there is an alternative way to open files, and I was explicitly told to please remember to close them in order to free up the resources they used or something like that, I will look into your method , thanks for the advice and the fix on the code runs like a charm now with no hassle. Much appreciate perfringo

Attached Files

Thumbnail(s)
   
Reply


Messages In This Thread
String handling - by YoungGrassHopper - Sep-14-2019, 10:30 AM
RE: String handling - by metulburr - Sep-14-2019, 10:41 AM
RE: String handling - by YoungGrassHopper - Sep-14-2019, 10:42 AM
RE: String handling - by YoungGrassHopper - Sep-15-2019, 07:02 AM
RE: String handling - by perfringo - Sep-15-2019, 07:32 AM
RE: String handling - by ndc85430 - Sep-15-2019, 07:34 AM
RE: String handling - by YoungGrassHopper - Sep-15-2019, 08:12 AM
RE: String handling - by snippsat - Sep-15-2019, 09:55 AM
RE: String handling - by YoungGrassHopper - Sep-15-2019, 12:01 PM
RE: String handling - by jefsummers - Sep-15-2019, 12:21 PM
RE: String handling - by YoungGrassHopper - Sep-15-2019, 12:33 PM
RE: String handling - by YoungGrassHopper - Sep-15-2019, 01:12 PM
RE: String handling - by newbieAuggie2019 - Sep-15-2019, 09:20 PM
RE: String handling - by perfringo - Sep-15-2019, 01:05 PM
RE: String handling - by perfringo - Sep-15-2019, 05:38 PM
RE: String handling - by YoungGrassHopper - Sep-15-2019, 08:28 PM
RE: String handling - by YoungGrassHopper - Sep-15-2019, 10:37 PM
RE: String handling - by jefsummers - Sep-16-2019, 12:47 AM
RE: String handling - by YoungGrassHopper - Sep-16-2019, 04:45 AM
RE: String handling - by perfringo - Sep-16-2019, 05:11 AM
RE: String handling - by YoungGrassHopper - Sep-16-2019, 05:23 AM
RE: String handling - by perfringo - Sep-16-2019, 06:09 AM
RE: String handling - by YoungGrassHopper - Sep-16-2019, 06:46 AM
RE: String handling - by buran - Sep-16-2019, 06:54 AM

Possibly Related Threads…
Thread Author Replies Views Last Post
Star python exception handling handling .... with traceback mg24 3 1,332 Nov-09-2022, 07:29 PM
Last Post: Gribouillis

Forum Jump:

User Panel Messages

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