Open file
Reading files
Writing files.
With statement
FileNotFoundError - OSError
Open takes two arguments: open(filename, mode) and returns a file object.
f = open(filename, mode).
f = open(‘file1.txt', 'w')
The first argument is a string containing the filename. The second argument is mode - 'r‘ read only, 'w' for only writing.
In ‘w’ mode, If an existing file with the same name exists it will be erased/truncated first.
open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)
Open opens a file and return a stream.
If file is not available or unable to open/restricted permissions/any other issue results in Raise OSError.
Least - open arguments
file is either a text or byte string giving the name (and the path
if the file isn't in the current working directory) of the file to be opened or an integer file descriptor of the file to be wrapped. (If a file descriptor is given, it is closed when the returned I/O object is closed, unless closefd is set to False.)
mode is an optional string that specifies the mode in which the file is opened. It defaults to 'r' which means open for reading in text mode. Other modes are ‘w‘, 'x‘, 'a’ etc.
f1 = open('file1.txt', 'r')
f1.readline() - will read one line at a time.
F1.read() – will read entire text and output as a string.
f1.readlines()
readlines() will read all lines and output into a list
with open(“file1.txt”) as f1: ftext = f1.readlines()
'r' open for reading (default)
'w' open for writing, truncating the file first
'x' open for exclusive creation, failing if the file already exists
'a' open for writing, appending to the end of the file if it exists
'b' binary mode
't' text mode (default)
'+' open a disk file for updating (reading and writing)
File object returned by open() is based on mode (‘r', ‘w', ‘x’ etc.) which is subclass of TextIOWrapper