Also see Python Filesystem and Path Libraries.
Files are opened with the built-in function open()
.
open(file)
: file may be a path-like object or a file descriptor. Returns a file object:TextIOWrapper
,BufferedIOBase
subclass or unbufferedFileIO
.mode='r'
:r
read (default),w
write,a
append,+
'rw',w+b
truncates (but notr+b
),b
binary,t
text (default),x
exclusive.buffering=-1
:0
=none, 1=line, ≥2=block. Default -1 is lines for text, system-chosen blocksize for binary.encoding=None
: Text mode only, default is platform-dependent. Seecodecs
.errors=None
: Handles codec errors.newline=None
: Used only for deprecatedmode='u'
universal newlines.closefd=True
: Close file arg if a file descriptor.opener=None
: A callable, defaultos.open
.
The socket
module is the standard BSD API. A buffered file
object wrapping a socket can be obtained with socket.makefile()
.
socket.makefile()
: Args similar toopen()
.mode
: Onlyr
,w
,b
allowed.- Socket must be blocking.
close()
does not close underlying socket.- Windows cannot mix the returned object with file-like objects.
Warnings:
sock.shutdown(socket.SHUT_WR)
on a Unix domain stream socket will shut down both directions (Ubuntu 18.04).