remove whitespace while reading file

General discussions and questions abound development of code with MicroPython that is not hardware specific.
Target audience: MicroPython Users.
Post Reply
User avatar
devnull
Posts: 473
Joined: Sat Jan 07, 2017 1:52 am
Location: Singapore / Cornwall
Contact:

remove whitespace while reading file

Post by devnull » Tue Jun 12, 2018 8:03 am

Code: Select all

      
      self.chunk = 2048
      with open(self.fdir+req['path'], 'rb') as html:
        head = self.head(req['path'])
        chunk = head + html.read(self.chunk - len(head))
        while chunk:
          res.sendall(chunk)
          chunk = html.read(self.chunk)
        res.close()
 
It tried strip() but that does not work, how can I compress the read (html) file by removing whitespaces and carriage returns before sending ?

User avatar
Roberthh
Posts: 3667
Joined: Sat May 09, 2015 4:13 pm
Location: Rhineland, Europe

Re: remove whitespace while reading file

Post by Roberthh » Tue Jun 12, 2018 8:24 am

e.g.
"".join(chunk.split())

User avatar
devnull
Posts: 473
Joined: Sat Jan 07, 2017 1:52 am
Location: Singapore / Cornwall
Contact:

Re: remove whitespace while reading file

Post by devnull » Tue Jun 12, 2018 9:51 am

Thanks, that results in:

Code: Select all

Error: join expects a list of str/bytes objects consistent with self object
Also tried:

Code: Select all

"".join(chunk.decode().split()).encode()
By that's no good either !

User avatar
Roberthh
Posts: 3667
Joined: Sat May 09, 2015 4:13 pm
Location: Rhineland, Europe

Re: remove whitespace while reading file

Post by Roberthh » Tue Jun 12, 2018 11:09 am

if chunk is a bytes object, you may need:


b"".join(chunk.split())

User avatar
pythoncoder
Posts: 5956
Joined: Fri Jul 18, 2014 8:01 am
Location: UK
Contact:

Re: remove whitespace while reading file

Post by pythoncoder » Wed Jun 13, 2018 7:10 am

The unicode support in Python 3 requires constant attention to detail regarding the difference between bytes (and bytearray) objects and strings. It still regularly catches me out...
Peter Hinch
Index to my micropython libraries.

Post Reply