Python Forum
supporting both str and bytes on write file
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
supporting both str and bytes on write file
#11
There is a difference between str and bytes. In addition, bytes could be unbuffered.
Depending on the type, you get different classes from io module back.

Here an example to show the different modes and buffered/unbuffered mode.
for mode, buffering in (("r", -1), ("rb", -1), ("w", -1), ("wb", -1), ("rb", 0), ("wb", 0)):
    with open("/dev/null", mode, buffering=buffering) as fd:
        bytes_mode = not hasattr(fd, "encoding")
        if bytes_mode:
            print(type(fd), "MODE:", fd.mode, "bytes")
        else:
            print(type(fd), "MODE:", fd.mode, "str")
Output:
<class '_io.TextIOWrapper'> MODE: r str <class '_io.BufferedReader'> MODE: rb bytes <class '_io.TextIOWrapper'> MODE: w str <class '_io.BufferedWriter'> MODE: wb bytes <class '_io.FileIO'> MODE: rb bytes <class '_io.FileIO'> MODE: wb bytes
PS:
A FileObject which was opened in raw mode, does not have the encoding attribute.
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
Reply
#12
so, where do i get the value of mode and buffering from? is there an attribute in the file object?
Tradition is peer pressure from dead people

What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.
Reply
#13
i see where i asked in a confusing way. the open i want to do is my own class of object over another, so it can accept an already-open object as the "name" argument.
Tradition is peer pressure from dead people

What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  supporting both strings and bytes in functions Skaperen 0 1,440 Nov-28-2019, 03:17 PM
Last Post: Skaperen

Forum Jump:

User Panel Messages

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