Professional Documents
Culture Documents
23 Class 12 FileHandling 1
23 Class 12 FileHandling 1
23 Class 12 FileHandling 1
Data Files
Python provides inbuilt functions for creating, writing and reading files. There are two types
of files that can be handled in python, normal text files and binary files (written in binary
language,0s and 1s).
• Text files: In this type of file, each line of text is terminated with a special character
called EOL (End of Line), which is the new line character (‘\n’) in python by default.
• Binary files: In this type of file, there is no terminator for a line and the data is stored
after converting it into machine understandable binary language.
Text File
Regular Text Files
Most associate plain text files with the file extension. txt on Microsoft Windows computers,
however, can be any non-formatted file. To view a plaintext file, a text editor, such as
Microsoft Notepad is used.
TSV (Tab Separated Files): when a tab character is used to separate the values stored, these
are called TSV files. these files can take the extension as .txt or .csv.
CSV (Comma Separated Values files): when a comma character is used to separate the
values stored, these are called CSV files. these files can take the extension as .txt or .csv.
Binary Files:
A Binary file stores the information in the form of a stream of bytes.
Note: The file should exist in the same directory as the Python script, otherwise, full address
of the file should be written.
Read and
Write and w+/w+b or Open the file for reading and writing. Unlike “r+” is doesn’t raise an
Open the file for writing and creates new file if it doesn’t exist. All
additions are made at the end of the file and no existing data can be
Open the file for reading and writing and creates new file if it
Append and doesn’t exist. All additions are made at the end of the file and no
Example2: In this example, we will open the file and printed its content.
# Reading from file
print (file.read ())
Example 3: In this example, we will be overwriting the contents of the sample file with the
below code:
# open the file using open () function
file = open ("sample.txt", 'w')
Example 3: In this example, we will be overwriting the contents of the sample file with the
below code:
# open the file using open () function
file = open ("sample.txt", 'w')
2. Method:readline()
Syntax: <filehandle>.readline([n])
Read line of input; if n is specified read at most n bytes.
Eg.,
file 1= open (“E:\\mydata\\info.txt”)
readInfo=file1.readline()
#1 line read
print (readInfo)
3. Method: readlines()
Syntax: <filehandle>.readlines()
Read all lines and returns them in a list.
Eg.,
file 1= open (“E:\\mydata\\info.txt”)
readInfo=file1.readline()
# all lines read
print (readInfo)
HOME ASSIGNMENT: