12 Computer Science-File Handling-Notes
12 Computer Science-File Handling-Notes
12 Computer Science-File Handling-Notes
COMPUTER SCIENCE
FILE HANDLING
NOTES
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.
In programming, Sometimes, it is not enough to only display the data on the console. Those
data are to be retrieved later on, then the concept of file handling comes. It is impossible to
recover the programmatically generated data again and again. However, if we need to do so,
we may store it onto the file system which is not volatile and can be accessed every time.
Here, comes the need of file handling in Python.
File handling in Python enables us to create, update, read, and delete the files stored on the
file system through our python program. The following operations can be performed on a
file.
In Python, File Handling consists of following three steps:
Open the file.
Process file i.e. perform read or write operation.
Close the file.
Types of File
There are two types of files:
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.
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.
Less prone to get corrupt as change Can easily get corrupted, corrupt on reflects as
soon as made and can be even single bit change
undone.
Store only plain text in a file. Can store different types of data
Widely used file format and can be Developed for an application and can be
opened in any text editor. can be opened in that only.
Opening and Closing Files : To perform file operation, it must be opened first then after
reading, writing, editing operation can be performed. To create 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. Once we are done working with the file, we
should close the file.
Closing a file releases valuable system resource. 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.
1 r - reading only. Sets file pointer at beginning of the file. This is the default
mode.
open() Function:
The key function for working with files in Python is the open() function.
"r" - Read - Default value. Opens a file for reading, error if the file does not exist`
"w" - Write - Opens a file for writing, creates the file if it does not exist
"x" - Create - Creates the specified file, returns an error if the file exists
In addition you can specify if the file should be handled as binary or text mode
To open a file for reading it is enough to specify the name of the file:
f = open("demofile.txt")
f = open("demofile.txt", "rt")
Because "r" for read, and "t" for text are the default values, you do not need to specify them.
Assume we have the following file, located in the same folder as Python:
The open() function returns a file object, which has a read() method for reading the content
of the file:
Example
f = open("demofile.txt", "r")
print(f.read())
If the file is located in a different location, you will have to specify the file path, like this:
Example
By default the read() method returns the whole text, but you can also specify how many
characters you want to return:
Example
f = open("demofile.txt", "r")
print(f.read(5))
Write to an Existing File
To write to an existing file, you must add a parameter to the open() function:
Example
f = open("demofile2.txt", "a")
f.write("Now the file has more content!")
f.close()
Example
f = open("demofile3.txt", "w")
f.write("Woops! I have deleted the content!")
f.close()
To delete a file, you must import the OS module, and run its os.remove() function:
Example
import os
os.remove("demofile.txt")
Check if File exist:
To avoid getting an error, you might want to check if the file exists before you try to delete
it:
Example
Check if file exists, then delete it:
import os
if os.path.exists("demofile.txt"):
os.remove("demofile.txt")
else:
print("The file does not exist")
Delete Folder
Example
import os
os.rmdir("myfolder")
CSV FILE (Comma separated value)
CSV (Comma Separated Values) is a file format for data storage which looks like a text file.
The information is organized with one record on each line and each field is separated by
comma.
CSV Advantages
CSV Disadvantages
• CSV allows to move most basic data only. Complex configurations cannot be
• Problems with importing CSV into SQL (no distinction between NULL and
quotes)
to import csv module for file operation/method call. For writing, we open file in ‘w’
writing mode using open () method which create newFile like object.
Through csv.writer() method ,we create writer object to call writerow() method to write
objects.
Similarly for reading, we open the file in ‘r’ mode and create newFile like object,further
we create newfilereader object using csv.reader() method to read each row of the file.
Three file opening modes are there ‘w’,’r’,’a’. ‘a’ for append After file operation close,
newFileWriter = csv.writer(newFile)
newFileWriter.writerow(['user_id','beneficiary'])
newFileWriter.writerow([1,'xyz'])
newFileWriter.writerow([2,'pqr'])
newFile.close()
newFileReader = csv.reader(newFile)
print (row)