0% found this document useful (0 votes)
3 views5 pages

Lecture 10 File Handling in Python

File handling in Python allows for versatile operations such as creating, reading, writing, appending, renaming, and deleting files, with support for various file types. The open() function is used to access files in different modes (e.g., read, write, append), and there are specific methods for reading and writing data. Additionally, Python's file handling is user-friendly and cross-platform, making it accessible for developers across different operating systems.

Uploaded by

noriana987
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)
3 views5 pages

Lecture 10 File Handling in Python

File handling in Python allows for versatile operations such as creating, reading, writing, appending, renaming, and deleting files, with support for various file types. The open() function is used to access files in different modes (e.g., read, write, append), and there are specific methods for reading and writing data. Additionally, Python's file handling is user-friendly and cross-platform, making it accessible for developers across different operating systems.

Uploaded by

noriana987
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

File Handling in Python

File handling in Python is a powerful and versatile tool that can be used to perform a wide
range of operations. Python treats files differently as text or binary and this is important. Each
line of code includes a sequence of characters and they form a text file. Each line of a file is
terminated with a special character, called the EOL or End of Line characters like comma {,}
or newline character. It ends the current line and tells the interpreter a new one has begun.

Advantages of File Handling

 Versatility: File handling in Python allows you to perform a wide range of operations,
such as creating, reading, writing, appending, renaming, and deleting files.
 Flexibility: File handling in Python is highly flexible, as it allows you to work with
different file types (e.g. text files, binary files, CSV files, etc.), and to perform different
operations on files (e.g. read, write, append, etc.).
 User–friendly: Python provides a user-friendly interface for file handling, making it
easy to create, read, and manipulate files.
 Cross-platform: Python file-handling functions work across different platforms (e.g.
Windows, Mac, Linux), allowing for seamless integration and compatibility.

Now, let us create a text file (text_file.txt) with the following dummy content

Hello
I am new to programming
Roll number 12

Working of open() Function in Python

To open a file we make use of open(), the syntax is mentioned below

f = open(filename, mode)
Where,
f = File Pointer, that points to start of the file.
filename = Name of the file
mode = It represents the purpose of the opening file

Modes in file handling can be of following types:


1. r: open an existing file for a read operation.
2. w: open an existing file for a write operation. If the file already contains some data
then it will be overridden but if the file is not present then it creates the file as well.
3. a: open an existing file for append operation. It won’t override existing data.
4. r+: To read and write data into the file. The previous data in the file will be
overridden.
5. w+: To write and read data. It will override existing data.
6. a+: To append and read data from the file. It won’t override existing data.
Let us see how to open a file in read mode

>>> f = open("text_file.txt", "r")

If a file does not exist, and you try to open in “r” mode, then the interpreter will show a error.

>>> f = open("text1_file.txt", "r")


Traceback (most recent call last):
File "<pyshell#1>", line 1, in <module>
f = open("text1_file.txt", "r")
FileNotFoundError: [Errno 2] No such file or directory:
'text1_file.txt'

Reading and Writing to text files in Python

There are two ways to write in a file.

1. write() : Inserts the string str1 in a single line in the text file.
File_object.write(str1)

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

Important Note: write() argument must be string, not list

There are three ways to read data from a text file.

1. 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])

2. readline() : Reads a line of the file and returns in form of a [Link] 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])

3. readlines() : Reads all the lines and return them as each line a string element in a list.
File_object.readlines()

Let’s us write a complete program to read the lines of text_file.txt file and print the same
using loops.
Approach 1 –
# a file named "text_file", will be opened with the reading mode.
f = open("text_file.txt", "r")

# This will print every line one by one in the file


for each in f:
print (each)

Hello
Approach 2 -
# Python code to illustrate read() mode
I am new to programming
file = open("text_file.txt", "r")
print ([Link]())
Roll number 12

Approach 3 – Output
# Python code to illustrate with()
with open("text_file.txt") as file:
data = [Link]()

print(data)

We can also split lines while reading files in Python. The split() function splits the variable
when space is encountered. You can also split using any characters as you wish.

# Python code to illustrate split() function


['Hello']
with open("text_file.txt", "r") as file:
data = [Link]()
['I', 'am', 'new', 'to', 'programming']
for line in data:
word = [Link]()
['Roll', 'number', '12']
print (word)
Output

Important Note:

file = open("Read_ex.txt", "r")


example1 = [Link]()

[Link]() will print all the values in the file. In doing so, the file handle will reach to the end
and then if you wish to use read(14) it won't print any thing Therefore, with seek(0), you first
bring the file handle back to start and then read(14) bytes.

[Link](0)
example2 = [Link](14)
print(example1)
print(example2)
Creating a File using the write() Function

Let’s see how to create a file and how the write mode works.

Example 1: In this example, we will see how the write mode and the write() function is used to
write in a file. The close() command terminates all the resources in use and frees the system of
this particular program.
Suppose, we wish to print the following lines in the pre-existing “text_file.txt” file. Then, lets
see what happens.
# Python code to create a file
file = open('text_file.txt','w')
[Link]("This is the write command")
[Link]("It allows us to write in a particular file")
[Link]()

Hello This is the write commandIt


allows us to write in a
I am new to programming particular file
Roll number 12

Initial content of FinalOutput


content of
text_file.txt text_file.txt

So, you must have understood that if a file already existed in the memory and you wish to write
some content to it, the content of the existing file will be overwritten by the new content. What
if the file does not exist? Will writing to a non-existing file give an error?

Try the following code and see what happens.


# Python code to create a file
file = open('Sample_text_file.txt','w')
[Link]("This is a new file. ")
[Link]("It do not exist in my system.)
[Link]()

If you didn’t get any error, it means that file was created and you can see the content of the file
using open().

You can also write to file using write ().


# Python code to illustrate with() alongwith write()
with open("[Link]", "w") as f:
[Link]("Hello World!!!")
Working of Append Mode
Append mode adds a data to a pre-existing (text_file.txt) file contents.

# Python code to illustrate append() mode


file = open('text_file.txt', 'a')
[Link]("This will add this line")
[Link]()

Hello
Hello
I am new to programming
I am new to programming
Roll number 12
Roll number 12
This will add this line
Initial content of text_file.txt Final content of text_file.txt

Practice Programs:

1. Read the content of a file using read(), readline() and readlines().

2. Copy the content of a file to another file after removing the vowels.
a. Without using functions
b. Using functions

3. Read the content of a file and display the count of Upper Case Letters, Lower Case
Letter, White Spaces, Digits and No. of Lines using Functions.

You might also like