0% found this document useful (0 votes)
20 views8 pages

File Handling

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views8 pages

File Handling

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 8

Computer Science (2024-25)

CLASS XII Code No. 083

FILE HANDLING IN PYTHON


Python provides built-in functions for creating, writing, and reading files. Two types of files 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.

Opening a Text File in Python


It is done using the open() function. No module is required to be imported for this function.
File_object = open(r"File_Name","Access_Mode")
Example: Here, file1 is created as an object for MyFile1 and file2 as object for MyFile2.

There are three ways to read txt file in Python:


∙ Using read()
∙ Using readline()
∙ Using readlines()
Reading From a File Using read()
read(): Returns the read bytes in form of a string. Reads n bytes, if no n specified, reads the
entire file.
File_object.read([n])
Reading a Text File Using readline()
readline(): Reads a line of the file and returns in form of a string.For specified n, reads at most n
bytes. However, does not reads more than one line, even if n exceeds the length of the line.
File_object.readline([n])
Reading a File Using readlines()
readlines(): Reads all the lines and return them as each line a string element in a list.
File_object.readlines()
Note: ‘\n’ is treated as a special character of two bytes.
In this example, a file named “myfile.txt” is created and opened in write mode ( "w" ). Data is
written to the file using write and writelines methods. The file is then reopened in read and
append mode ( "r+" ). Various read operations, including read , readline , readlines , and
the use of seek , demonstrate different ways to retrieve data from the file. Finally, the file is
closed.

Example program:
file1 = open("myfile.txt", "w")

file1 = open("myfile.txt", "w")


L = ["This is Delhi \n", "This is Paris \n", "This is London \n"]

# \n is placed to indicate EOL (End of Line)


file1.write("Hello \n")
file1.writelines(L)
file1.close() # to change file access modes

file1 = open("myfile.txt", "r+")

print("Output of Read function is ")


print(file1.read())
print()

# seek(n) takes the file handle to the nth


# byte from the beginning.
file1.seek(0)

print("Output of Readline function is ")


print(file1.readline())
print()

file1.seek(0)

# To show difference between read and readline


print("Output of Read(9) function is ")
print(file1.read(9))
print()

file1.seek(0)

print("Output of Readline(9) function is ")


print(file1.readline(9))

file1.seek(0)
# readlines function
print("Output of Readlines function is ")
print(file1.readlines())
print()
file1.close()
Write to Text File in Python
There are two ways to write in a file:
∙ Using write()
∙ Using writelines()
write(): Inserts the string str1 in a single line in the text file.
File_object.write(str1)

writelines(): For a list of string elements, each string is inserted in the text file.Used
to insert multiple strings at a single time.
File_object.writelines(L) for L = [str1, str2, str3]

Appending to a File in Python


In this example, a file named “myfile.txt” is initially opened in write mode ( "w" ) to
write lines of text. The file is then reopened in append mode ( "a" ), and “Today” is
added to the existing content. The output after appending is displayed using
readlines . Subsequently, the file is reopened in write mode, overwriting the
content with “Tomorrow”. The final output after writing is displayed using
readlines.
Closing a Text File in Python
Python close() function closes the file and frees the memory space acquired by that file. It is
used at the time when the file is no longer needed or if it is to be opened in a different file
mode.
File_object.close()

Reading binary files in Python


In computer science, binary files are stored in a binary format having digits 0’s and 1’s. For
example, the number 9 in binary format is represented as ‘1001’. In this way, our computer
stores each and every file in a machine-readable format in a sequence of binary digits. The
structure and format of binary files depend on the type of file. Image files have different
structures when compared to audio files. However, decoding binary files depends on the
complexity of the file format.

Python Read A Binary File


To read a binary file,
Step 1: Open the binary file in binary mode
To read a binary file in Python, first, we need to open it in binary mode (‘”rb”‘). We can use the
‘open()’ function to achieve this.
Step 2: Create a binary file
To create a binary file in Python, You need to open the file in binary write mode ( wb ). For more
refer to this article.
Step 3: Read the binary data
After opening the binary file in binary mode, we can use the read() method to read its content
into a variable. The” read()” method will return a sequence of bytes, which represents the
binary data.
Step 4: Process the binary data
Once we have read the binary data into a variable, we can process it according to our specific
requirements. Processing the binary data could involve various tasks such as decoding binary
data, analyzing the content, or writing the data to another binary file.
Step 5: Close the file
After reading and processing the binary data, it is essential to close the file using the “close()”
method to release system resources and avoid potential issues with file access.

Reading binary data into a byte array


This given code demonstrates how to read binary data from a file into a byte array and then To
read binary data into a binary array print the data using a while loop. Let’s explain the code
step-by-step:
Open the Binary File
This line opens the binary file named “string.bin” in binary mode (‘”rb”‘). The file is opened for
reading, and the file object is stored in the variable ‘file’.

Close the Binary File


Finally, after the loop has finished reading and printing the data, we close the binary file using
the ‘close()’ method to release system resources.
Reading and Writing CSV Files in Python
Python contains a module called csv for the handling of CSV files. The reader class from the
module is used for reading data from a CSV file. At first, the CSV file is opened using the open()
method in ‘r’ mode(specifies read mode while opening a file) which returns the file object then
it is read by using the reader() method of CSV module that returns the reader object that iterates
throughout the lines in the specified CSV document.
Syntax:
csv.reader(csvfile, dialect='excel', **fmtparams
Note: The ‘with‘ keyword is used along with the open() method as it simplifies exception handling
and automatically closes the CSV file.
Example:
Consider the below CSV file –

Writing to CSV file


csv.writer class is used to insert data to the CSV file. This class returns a writer object which is
responsible for converting the user’s data into a delimited string. A CSV file object should be
opened with newline=” otherwise, newline characters inside the quoted fields will not be
interpreted correctly.
Syntax:
csv.writer(csvfile, dialect='excel', **fmtparams)
csv.writer class provides two methods for writing to CSV. They are writerow() and writerows().
∙ writerow(): This method writes a single row at a time. Field row can be written using this
method.
Syntax:
writerow(fields)

∙ writerows(): This method is used to write multiple rows at a time. This can be used to write
rows list.
Syntax:
writerows(rows)

We can also write dictionary to the CSV file. For this the CSV module provides the csv.DictWriter
class. This class returns a writer object which maps dictionaries onto output rows.
Syntax:
csv.DictWriter(csvfile, fieldnames, restval=”,
extrasaction=’raise’, dialect=’excel’, *args, **kwds)
csv.DictWriter provides two methods for writing to CSV. They are:
∙ writeheader(): writeheader() method simply writes the first row of your csv file using the
pre-specified fieldnames.
Syntax:
writeheader()
∙ writerows(): writerows method simply writes all the rows but in each row, it writes only the
values(not keys).
Syntax:
writerows(mydict)

You might also like