File Handling
File Handling
File Handling
Output
1.File Handling
2.Database
Step 3)Pass file path and access mode to the open() function
fp= open(r"File_Name", "Access_Mode"). For example, to open and
read: fp = open('sample.txt', 'r')
Srinivas Rao Aitha - Python Full Stack
Trainer
Python –File Handling
Please Note:
The above file structure is in my Laptop, yours File path
will be different
The above function will return the file object which we can use to
read or write to a file. Srinivas Rao Aitha - Python Full Stack
Trainer
Python –File Handling
Example
The difference between this and the write mode is that the
file’s content will not be truncated or deleted in this mode.
Closing a File
We need to make sure that the file will be closed properly after
completing the file operation. It is a bad practice to leave your
files open.
It releases the resources that have been tied up with the file. By
this space in the RAM can be better utilized and ensures a better
performance.
It ensures better garbage collection.
There is a limit to the number of open files in an application. It is
always better to close the file to ensure that the limit is not
crossed.
If you open the file in write or read-write mode, you don’t know
when data is flushed.
Srinivas Rao Aitha - Python Full Stack
Trainer
Python –File Handling
II ) Reading a file
We can avoid this by wrapping the file opening code in the try-
except-finally block.
The following are the main advantages of opening a file using ‘with’
statement
For example, If you want to read the first five lines from a
text file, run a loop five times, and use the readline()
method in the loop’s body. Using this approach, we can
read a specific number of lines.
We can read the first few set of lines from a file by using
the readline() method. Run a loop fo n times using for loop
and range() function, and use the readline() method in the
loop’s body.
Example:
To write the contents into a file, we have to open the file in write
mode. Open a file using the built-in function called open(). This
function takes two parameters, namely filename, and access
mode, and returns the file pointer.
With the access mode set to a, the open function will place
filehandle at the end of the file, and then we can add new
text at the end of the existing file using the write() and
writelines() functions.