Professional Documents
Culture Documents
Opening a File:
It is done using the open() function.
No module is required to be imported for this function.
open() function:
Before performing any operations on a file, first we need to
open the file.
# The Text file named "Samp1", will be opened in the reading mode.
# This will print every line of the text file one by one.
Example:
The open command will open the file in the read mode
and the for loop will print each line present in the file.
The built-in function
open()
If the file does not exist in the same directory as the python
program file then full path of the file should be written on place
of filename preceded by r.
Note: Here, r refers to raw string such that there is no special
meaning for any character. That means, r is placed before
filename to prevent the characters in filename string to be
treated as special character.
Example: f=open(r”C:\temp\data.txt”, ”r”)
The built-in function
open()
The r makes the string raw, that is, it tells that the string is
without any special characters. The r can be ignored if the file is
in the same directory as that of Python.
Text Files
Program No: 2
# The Text file named “data", will be opened in the reading mode.
# This will print every line of the text file one by one.
# The Text file named “data", will be opened in the reading mode.
# This will print every line of the text file one by one.
Closing a File:
It is done using the close() method of its file-object/ file
handle.
It breaks the link of the file-object/ file handle and
the file on the disk.
It is very important that an opened file has to be closed
at the end of its use in the program.
In Python, files are automatically closed at the end of the
program but it is a good practice to close the files
explicitly.