File Handling
File Handling
File
• File is a named location on the system storage which records data for later
access. It enables persistent storage in a non-volatile memory i.e. Hard disk.
• To read or write to a file, you need to open it first. To open a file in Python, use its
built open() function. This function returns a file object, i.e., a handle. You can use
it to read or modify the file.
The open command will open the file in the read mode and the for loop
will print each line present in the file.
• There is more than one way to read a file in Python. If you need to
extract a string that contains all characters in the file then we can
use file.read(). The full code would work like this:
# Python code to illustrate read() mode
file = open("file.text", "r")
print (file.read())
• Another way to read a file is to call a certain number of characters like
in the following code the interpreter will read the first five characters
of stored data and return it as a string
• The close() command terminates all the resources in use and frees the
system of this particular program.
Append in a file