VKS-LEARNING HUB
In allthe programs we have seen so far, the data provided to a Python program was
through the command line and it is not saved.
If a program has to be run again, the user must again input data.
Similarly, the output of a program appears on the computer screen but is not
saved anywhere permanently.
In practical programming it is necessary to provide data to a program from a file, and
save the output data into a file. The output data may be required for further processing.
A file is a collection of data.
This data may be, for example,
students’ data (Roll No, Name, Address, Tel No, Grades,...),
employee data (EmpID, Name, Dept, Designation, Salary…), etc.
A file could also be used to store a picture audio, video, etc.
Concept of File:
3.
VKS-LEARNING HUB
When aprogram needs to save data for later
use, it writes the data in a file. The data can be
read from the file at a later time.
What is a file?
A file is a sequence of bytes on the disk/permanent
storage where a group of related data is stored. File is
created for permanent storage of data.
4.
VKS-LEARNING HUB
7-4
Saving datain a file = “writing data to” the file
Output file = file that data is written to
Retrieving data from a file = “reading data from” the file
Input file = file that data is read from
File Access Methods
Two ways to access data stored in files:
• Sequential Access - access data from the beginning
of the file to the end of the
file
• Direct (random) Access- directly access any piece of
data in the file without
reading the data that
Terms
5.
VKS-LEARNING HUB
Types ofFiles:
(i) Text files - A file whose contents can be viewed using a
text editor is called a text file. A text file is simply a
sequence of ASCII or Unicode characters. Python
programs, contents written in text editors are some of the
example of text files.
(ii) Binary files- A binary file stores the data in the same
way as as stored in the memory. The .exe files,mp3 file,
image files, word documents are some of the examples of
binary files.we can’t read a binary file using a text editor.
6.
VKS-LEARNING HUB
Text fileBinary file
Its Bits represent character. Its Bits represent custom Data
Store only plain text in a file. Can store different types of data (audio,
text, image) in a single file
Widely used file format and can be
opened in any text editor.
Developed for an application and can be
opened in that application only.
Mostly .txt and .rtf are used as extensions
to text files.
Can have any application defined
extension.
Text file is human readable because
everything is stored in terms of text.
In binary file everything is written in
terms of 0 and 1, therefore binary file is
not human readable.
Newline(‘n’) & EOF character conversion
takes place
No such character conversion take place
7.
VKS-LEARNING HUB
File handlingin Python enables us to create, update,
read, and delete the files stored on the file system
through our python program.
When we want to read from or write to a file we need
to open it first. When we are done, it needs to be
closed, so that resources that are tied with the file are
freed.
Hence, in Python, a file operation takes place in the
following order.
1.Open a file
2.Read or write (perform operation)
3.Close the file
8.
VKS-LEARNING HUB
Opening
Tocreate any new file then too it must be opened.
On opening of any file ,a file relevant structure is created in memory as well as
memory space is created to store contents.
Closing
Once we are done working with the file, we should close the file.
Closing a file releases valuable system resources.
In case we forgot to close the file, Python automatically close the file when
program ends or file object is no longer referenced in the program.
However, if our program is large and we are reading or writing multiple files that
can take significant amount of resource on the system.
If we keep opening new files carelessly, we could run out of resources. So be a
good programmer , close the file as soon as all task are done with it.
Opening and Closing Files
9.
VKS-LEARNING HUB
Buffer: transferof data between RAM and backing storage cannot be
done directly because application (program) has no clue about the backing
storage. It is the OS (Operating System) that controls the backing storage.
Hence the solution is to create a temporary storage in the RAM called
buffer to transfer data between RAM and backing storage.
Writing into a file: data from the variable(s) located in the RAM to be transferred to the
buffer by the Python Program (or any application / program) and data from the buffer to
be transferred to the file located in the backing storage by the OS (Operating System).
Reading from a file: data from file(s) located in the backing storage to be transferred to
the buffer by the OS (Operating System) and data from buffer to be transferred to the
variable(s) located in the RAM by the Python Program (or any application / program).
10.
VKS-LEARNING HUB
Opening aFile
General format:
file_variable = open(filename, mode, buffering)
file_variable is the name of the variable that will reference the file object
filename is a string specifying the name of the file
mode is a string specifying the mode (reading, writing, etc.)
Buffering = for no buffering set it to 0.for line buffering set it to 1.if it is
greater than 1 ,then it is buffer size. if it is negative then buffer size is
system default
Python has a built-in function open() to open a file. This function returns a
file object, also called a handle, as it is used to read or modify the file
accordingly. It also create a file if file doesn't exist in write mode
11.
VKS-LEARNING HUB
Python FileModes
Mode Description
'r' Open a file for reading. (default)
'w'
Open a file for writing. Creates a new file if it does not exist or
truncates the file if it exists.
'a' Open for appending at the end of the file without truncating it. Creates
a new file if it does not exist.
't' Open in text mode. (default)
'b' Open in binary mode.
'+' Open a file for updating (reading and writing)
'x' Open a file for exclusive creation. If the file already exists, the
operation fails.
f = open("test.txt") # equivalent to 'r' or 'rt’
f = open("test.txt",'w') # write in text mode
f = open("img.bmp",'r+b') # read and write in binary mode
12.
VKS-LEARNING HUB
The fileobject attributes:
Once a file is opened and you have one file object, you can get various
information related to that file.
Attribute Description
file.closed Returns true if file is closed, false otherwise.
file.mode Returns access mode with which file was opened.
file.name Returns name of the file.
File.encoding Encoding used for byte string conversion
13.
VKS-LEARNING HUB
7-13
Writing Datato a File
The built-in write() function is used to write data to the file in
the form of string. It does return value of int type which is
the length of string written. Due to buffering, the string may
not actually show up in the file until the flush() or close()
method is called.
The general syntax of write() is:
file_varaible.write(string)
• file_variable – variable that references a file
object
• write - file object used to write data to a file
• string - string that will be written to the file
VKS-LEARNING HUB
7-15
Writing Datato a File
The file object writelines() method used to write a list of
string or iterable to a file.
The general syntax of writelines() is:
file_varaible.writelines(list)
• file_variable – variable that references a file
object
• writelines - file object method used to write data
to a file
• list - List of Strings
VKS-LEARNING HUB
File1 =open("filename")
opens the given file for reading, and returns a file object
File1.read() - file's entire contents as a
string
File1.readline() - next line from file as a string
FIle1.readlines() - file's contents as a list of
lines
the lines from a file object can also be read using a for
loop
There are four techniques for reading a file and all these
techniques work by starting at the current file cursor.
Techniques for Reading Files
18.
VKS-LEARNING HUB
1. Usingread() method
This techniques is used to:
(i) Read the contents of a file into a single string, or
(ii) To specify exactly how many characters to read.
This reads the entire file from the current cursor location to the end
of the file, and then moves the cursor to the end of the file.
To read the contents of the file into a single string, we use the followi
ng syntax:
<string variable>= <file variable>.read()
19.
VKS-LEARNING HUB
2. Usingreadlines([size]) method
This technique is used to read each lineof a text file and store it in a
separatestring in a list. After reading the lines, the cursor moves to the
end of the file.
Each line ends with the newline character ‘n’ is a part of string.
To read the contents of the file into a single string, we use the following synt
ax:
<string variable>= <file variable>.readlines([size])
20.
VKS-LEARNING HUB
3. Usingreadline([size]) method
Read no of characters from file if size is mentioned till
Otherwise reads till new line character.
returns empty string on EOF.
This technique is used to read one lineof a text file including the newline character
To read the contents of the single line, we use the following syntax:
<string variable>= <file variable>.readline([size])
21.
VKS-LEARNING HUB
This techniquesis used to carry out the same action on each line of a file.
4. Using for x in file loop method
• A file handle open for read can be treated as a sequence of strings where
each line in the file is a string in the sequence
• We can use the for statement to iterate through a sequence