author | type | category | links | practiceQuestion | revisionQuestion | |||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
SebaRaba |
normal |
how-to |
|
|
|
Reading from and writing to files in Python 3 can be done using the open()
function. This will create a file
object, which can be used to call other support methods associated with it.
Consider the following syntax:
obj = open(f_name, [access_mode],
[buffering])
Here's the disambiguation of its arguments:
f_name
: string value that contains the name of the fileaccess_mode
: it determines the mode in which the file has to be opened:read
,write
,append
buffering
: there are two important values0
(means no buffering) or1
(means line buffering is performed). If the value is greater than1
then that will be considered the buffer's size
The supported modes for opening a file are:
a
: Opens the file forappending
. With the file pointer being at the end of the filer
: Opens the file forreading
. With the file pointer being at the beginning of the filew
: Opens the file forwriting
. Overwrites the file if it exists. If the file doesn't exist it will create a new filea+
: Opens the file for bothreading
andappending
. The file pointer is at the end of the filer+
: Opens the file for bothreading
andwriting
. The file pointer is place at the beginning of the filew+
: Opens the file for writing and reading as well. Overwrites the existing file. If it doesn't exist, creates a new fileab/rb/wb
: Opens the file forappending
/reading
/writing
in binary format
Always pay attention to where the file pointer is. That is mainly because when we append something a
to a file the pointer stays at the end of the file. If we want to print it we need to bring the pointer back to the beginning. This can be done using seek()
method (eg. seek(0) will move the pointer to the beginning of the file.)
Note that every file
object has the following attributes:
file.closed
: returnstrue
if the file is closed andfalse
otherwisefile.mode
: returns which mode the file was opened infile.name
: returns the name of the file
Consider the following example:
# Open file.txt and print file name
obj = open("doc.txt","w")
print("The file name is: ", obj.name)
# Output: The file name is: doc.txt
print("The file mode is: ", obj.mode)
# Output: The file mode is: w
# this means write
Suppose we want to open a file for both reading
and appending
. Fill the gaps accordingly:
file = open('practice.py', 'a')
file.write('Append this')
file.seek(0)
open
a+
seek
a
write
append
w
Suppose we want to open a file and write something to it. Fill the gaps accordingly:
file = open('practice.txt', '???')
file.???('this is my new file')
w
write
r
read