In this post
and subsequent posts, I am going to explain how to open, read and write to file.
How to open file
To read data
from a file (or) to write data to a file, we need a reference object that
points to file. ‘open’ method is used to get a file object.
open(file,
mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True,
opener=None)
'open'
function opens file in specific mode and
return corresponding file object. Throws OSError, if it is unable to open a
file.
Parameter
|
Description
|
file
|
Full path
of the file to be opened.
|
mode
|
Specifies
the mode, in which the file is opened. By default file opens in read mode.
|
buffering
|
0: Switch
off the buffer (only allowed in binary mode)
1: Line
buffering (only usable in text mode)
>1:
Specify the size of buffer in bytes.
If you
don't specify any value, by default buffering works like below.
a.
Binary
files are buffered in fixed-size chunks; the size of the buffer is chosen
using a heuristic trying to determine the underlying device’s “block size”
and falling back on io.DEFAULT_BUFFER_SIZE.
b.
“Interactive”
text files use line buffering.
|
encoding
|
Type of
encoding used to encode/decode a file. This value should be used in text
mode. if encoding is not specified the encoding used is platform dependent.
|
errors
|
Specifies
how encoding and decoding errors are to be handled. This cannot be used in
binary mode
|
newline
|
controls
how universal newlines mode works. A manner of interpreting text streams in
which all of the following are recognized as ending a line: the Unix
end-of-line convention '\n', the Windows convention '\r\n', and the old
Macintosh convention '\r'.
|
closefd
|
If closefd
is False and a file descriptor rather than a filename was given, the
underlying file descriptor will be kept open when the file is closed. If a
filename is given closefd must be True (the default) otherwise an error will
be raised
|
Following
are different modes that you can use while opening a file.
Mode
|
Description
|
'r'
|
open for
reading
|
'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)
|
For example,
data.txt contains following data.
data.txt
First line
Second line
Third line
Fourth line
>>> f=open("/Users/harikrishna_gurram/data.txt") >>> >>> f.read() 'First line\nSecond line\nThird line\nFourth line\n'
No comments:
Post a Comment