Removing Whitespaces after Reading from File

Preview




Removing Whitespaces after Reading from File

read( ), readline( ), readlines( ) functions are used to read data from file. All these functions also read the leading (at beginning) and trailing (at ending) whitespaces  i.e. spaces or tabs or newlines character. If we want to remove these trailing and leading whitespaces, we can use strip( )functions [rstrip( ), lstrip( )] as:

  • strip( ) removes the given character from both ends.
  • rstrip ( ) removes the given character from trailing end e.,right end.
  • lstrip( ) removes the given character from leading end e., left end.

1. Removing EOL ‘\n’ character from the line read from the file.

Fh = file (“poem.txt, “r”)
Line =fh.readline( )
Line = line.rstrip(‘\n’)

2. Removing the leading whilespaces from the line read from the file

Line = file (“poem.txt, “r”)
Line = line.lstrip( )




Lesson tags: create data file in python, Data file Handling in Python
Back to: Python Programming Tutorial