0% found this document useful (0 votes)
0 views13 pages

Unit 4

This document provides an overview of Python file operations, including reading and writing files, file modes, and the importance of file handling in Python. It explains how to use built-in functions such as open(), read(), write(), and close(), along with examples for each operation. Additionally, it covers file attributes, the use of the with statement for automatic file closure, and methods like seek() for manipulating the file pointer.

Uploaded by

manishxyz416
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)
0 views13 pages

Unit 4

This document provides an overview of Python file operations, including reading and writing files, file modes, and the importance of file handling in Python. It explains how to use built-in functions such as open(), read(), write(), and close(), along with examples for each operation. Additionally, it covers file attributes, the use of the with statement for automatic file closure, and methods like seek() for manipulating the file pointer.

Uploaded by

manishxyz416
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/ 13

PYTHON PROGRAMMING (BCC302)

(Unit 4)

IV Python File Operations: Reading files, Writing files in python, Understanding read functions,
read(), readline(), readlines(). Understanding write functions, write() and writelines() Manipulating
file pointer using seek Programming, using file operations. 04

File handling in Python (also known as Python I/O) involves the reading and writing process and
many other file handling options. The built-in Python methods can manage two file types, text and
binary files, but they encode data differently.
A text file consists of a series of lines. And each text line consists of several characters. The end of
the line (EOL) signifies the ending of each line in a text file. There are several special characters
used as EOL, but the most common are comma {,} and new lines.

How to write to a file using Python?

Take an example to understand the standard steps used during File Handling in Python.
Opening a file to write.
• Appending and writing to a file.
• Closing a file
Why File Handling Is Important In Python?

The concept of file handling can also use in other programming languages, but it is complicated or
time-consuming. Unlike other programming languages, it is easy to implement Python file handling.
Also, it is important to know how to read the data from a given file whenever you want to analyses
the data. All of these make the file handling concept extremely important.
Python offers built-in functions to open, write, read, close and delete files. Let us start by opening a
file.
Open a file in Python

To read or write to a file, you must first open it. The built-in Python function open() used to open a
file. This function takes two arguments, one file name, and the other mode (read mode, write mode)
to open the file. It returns a file object that is used together with different functions. We use the
following syntax to open a file in python.
Syntax of the Python open function:
file object = open(file_name [, access_mode][, buffering])
Below are the parameter details.

<file_name> – It‘s a string refers to the file you want to access.


<access_mode> – The access_mode sets the mode to open the file,e.g., read, write, append, and so
on. The parameter is optional. It is set to read-only <r> by default. In this mode, after reading from
the file, we get data in text form.
The binary mode, on the other hand, returns bytes. It is best to access non-text files such as an image
or Exe files.
<buffering> – The buffer indicates whether or not a buffer made. The default value is 0, meaning
that buffering will not occur. When the value is 1, line buffering occurs when you access the file. If it
is more than 1, the buffer action will execute according to the buffer size. The default behaviour
considered in the case of a negative value.

Python File Operation

A file is a named location used for storing data. For example, main.py is a file that is always used to

store Python code.

Python provides various functions to perform different file operations, a process known as File

Handling.

Opening Files in Python

In Python, we need to open a file first to perform any operations on it—we use the open() function to

do so. Let's look at an example:


Suppose we have a file named file1.txt.
Opening a File in
Python

To open this file, we can use the open() function.

file1 = open("file1.txt")

Here, we have created a file object named file1. Now, we can use this object to work with files.

Reading Files in Python

After we open a file, we use the read() method to read its content. For example,

Suppose we have a file named file1.txt.

Reading a File in Python

Now, let's read the content of the file.

# open a file in read mode


file1 = open("file1.txt")

# read the file content


read_content = file1.read()
print(read_content)

Output

This is a test file.


Hello from the test file.

In the above example, the code file1.read() reads the content of the file and stores it in

the read_content variable.

Writing to Files in Python

To write to a Python file, we need to open it in write mode using the w parameter.

Suppose we have a file named file2.txt. Let's write to this file.

# open the file2.txt in write mode


file2 = open('file2.txt', 'w')

# write contents to the file2.txt file


file2.write('Programming is Fun.\n')
file2.write('Programiz for beginners\n')

When we run the above code, we will see the specified content inside the file.

Writing to a Python File

Be Careful While Writing to a File


Closing Files in Python

When we are done performing operations on the file, we need to close the file properly. We use
the close() function to close a file in Python. For example,

# open a file
file1 = open("file1.txt", "r")

# read the file


read_content = file1.read()
print(read_content)

# close the file


file1.close()

Output

This is a test file.


Hello from the test file.

Note: Closing a file will free up the resources that are tied to the file. Hence, it is a good

programming practice to always close the file.

Opening a Python File Using with...open

In Python, there is a better way to open a file using with...open. For example,

with open("file1.txt", "r") as file1:


read_content = file1.read()
print(read_content)

Output

This is a test file.


Hello from the test file.

Here, with...open automatically closes the file, so we don't have to use the close() function.
Python file modes

When working with the Python file, you have to use modes for specific operations such as creating,
reading, writing, adding etc. It referred to Python file modes in file handling.
Modes Description

r Opens a file for reading only.

rb Opens a file for reading only in binary format.

r+ Opens a file for both reading and writing.

rb+ Opens a file for both reading and writing in binary format.

w Opens a file for writing only.

wb Opens a file for writing only in binary format.

w+ Opens a file for both writing and reading.

wb+ Opens a file for both writing and reading in binary format.

a Opens a file for appending.

ab Opens a file for appending in binary format.

a+ Opens a file for both appending and reading.

ab+ Opens a file for both appending and reading in binary format.

Take a look at this program and analyse how the reading mode works:
1 # a file named "file", will be opened with the reading mode.

2 file = open('file.txt', 'r')

3 # Each line will be printed one by one in the file

4 for each in file:

5 print (each)

The open command opens the file in reading mode and prints each line of the file with for loop.
In Python, there is more than one way to read a file. If you need to extract a string with all of the
characters in the file, we can use the.read(). The entire code works like this:
1 # Python code to illustrate read() mode

2 file = open("file.text", "r")

3 print (file.read())
Another way to read a file is to call a number of characters like in the code below. The interpreter
will read and return the first five characters of the stored data as a string:
1 # Python code to illustrate read() mode character wise

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

3 print (file.read(5))

The Python file object attributes

When you call the Python open() function, an object that is the filehandle is returned. You should
also know that Python files have several attributes linked. And we can use the file handle to list the
file attributes.
Please run through the table below to learn more about the file attributes.
Attribute Description

<file.closed> For a closed file, it returns true whereas false otherwise.

<file.mode> Returns the file opening access mode.

<file.name> Returns the file name.

Returns a boolean to suggest if a space char is added in the output <print> command
<file.softspace>
before it is printed another values.

Example: Python file attribute in action


1 #Open a file in write and binary mode.

2 file = open("app.log", "wb")

3 #Display file name.

4 print "File name: ", file.name

5 #Display state of the file.

6 print "File state: ", file.closed

7 #Print the opening mode.

8 print "Opening mode: ", file.mode

9 #Output the softspace value.

10 print "Softspace flag: ", file.softspace

1 File name: app.log

2 File state: False

3 Opening mode: wb
4 Softspace flag: 0

Perform Write operation

First of all, open it with a mode (read/write/append) while you are ready to enter data to a file.
You can even do the same with the mode append. If you have also used the <w> mode, the existing
data from the file will delete. It would help if you, therefore, took note of this fact when you choose
it.
The write() file method

Python provides a write() method to write a string or bytes sequence to a file. This function returns a
number that is the size of data stored in a single Write call.
Example: Read/Write to a File in Python
1 # Python code to create a file

2 file = open('file.txt','w')

3 file.write("This is the write command")

4 file.write("It allows us to write in a particular file")

5 file.close()

The close() command ends all used resources and frees the system from the specific program.
In the above example, the statement f=open(―file.txt‖, ―w‖) opens file.txt in write mode, returns the
file object and assigns it to the variable f in the open method. ―w‖ specifies the writable file. Next,
we‘ve got to put some data into the file. In the file, a string saved in the file.write(―Hello! Python‖).
Finally, file.close() closes the object file.
You find ―file.txt‖ created on your computer when you run the above code. You can view the
contents by opening an editor, such as Notepad.
Python provides the writelines() method for saving the contents of the list object in a file. Since the
character of the new line is not automatically written to the file, the character must be given in the
string.
Example: Write Lines to File
1 lines=["Hello world.\n", "Welcome to Technology.\n"]

2 f=open("D:\file.txt","w")

3 file.writelines(lines)

4 file.close()

Close a file in Python


When your work finished, it is always the best practice to close a file. Python, however, runs a
garbage collector to clean the unused objects.
The close() file method

Python provides the <close()> method to close a file.


Close operation in Python

The most basic way is to call the close() method of Python.


1 file = open("app.log",encoding = 'utf-8')

2 file.close() # do file operations.

Close with try-catch

Say, if there is an exception during certain operations on the file. In this case, the code leaves the file
without closing. It‘s, therefore, better to insert the code into a <try-finally> block.
1 try:

2 file = open('app.log', encoding = 'utf-8')

3 # do file operations.

4 finally:

5 file.close()

Even if there is an exception, the above code ensures that your file is closed properly.
Auto close using ‘with’

The WITH clause is another way of closing a file. It ensures that when the block executes within the
WITH clause, the file is closed. The beauty of this method is that the close() method does not need to
call explicitly.
1 with open('app.log', encoding = 'utf-8') as file:

2 #do any file operation.

Perform Read operation in python

First of all, to read data from a file, you need to open it in reading mode. You can then call any of the
Python methods for reading from a file.
Three different methods have provided to read file data.

• readline():
read characters from the current reading position to the newline character.
• read(chars): reads the number of characters that are specified starting from the current position.
• readlines(): reads all lines until file end and returns an object list.
Usually, we use Python <read(size)> to read the file content up to the size. If you don‘t pass the size,
then the whole file will read.
Example: Read from a File in Python
1 with open('app.log', 'w', encoding = 'utf-8') as f:

2 file.write('my first file\n') #first line

3 file.write('This file\n') #second line

4 file.write('contains three lines\n') #third line

5 f = open('app.log', 'r', encoding = 'utf-8')

6 print(file.read(10)) # read the first 10 data

7 #'my first f'

8 print(file.read(4)) # read the next 4 data

9 #'file\n'

10 print(file.read()) # read in the rest till end of file

11 #'This file\ncontains three lines\n'

12 print(file.read()) # further reading returns empty sting

13 #''

Example: Reading Lines


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

2 line = file.readline()

3 print(line)

4 file.close()

We must open the file in ‗r‘ mode. The readline() method returns the first line and points to the
second line in the file.
Use the While Loop to read all lines from a file, as shown below.
Example: Reading Lines
1 file = open("D:\file.txt","r")

2 line = file.readline()

3 while line!='':

4 print(line)

5 line = file.readline()
Working of append() mode

Let‘s see how the append mode works:


1 # Python code to illustrate append() mode

2 file = open('file.txt','a')

3 file.write("This will add this line")

4 file.close()

There are also several other commands in File handling used to handle multiple tasks such as:
1 Rstrip(): This function removes spaces from the right side for each line of a file.

2 Lstrip(): This function removes spaces from the left side of each file line.

It is intended to provide much cleaner syntax and exceptions handling when working with code. It
explains why it is good to practise, if applicable, to use them with a statement. It is useful because any
opened files will be automatically closed after one is done automatically by this method.
Example:
1 # Python code to illustrate with()

2 with open("file.txt") as file:

3 data = file.read()

4 # do something with data

Using write along with with() function

We can also use write function along with with() function:


1 # Python code to illustrate with() alongwith write()

2 with open("file.txt", "w") as f:

3 file.write("Hello World!!!")

split() using file handling

We can also split lines with Python file handling. This splits the variable when there is space. You
can split by any character as we like. The code is here:
1 # Python code to illustrate split() function

2 with open("file.text", "r") as file:

3 data = file.readlines()

4 for line in data:

5 word = line.split()
6 print (word)

Seek() Method

Use the seek() function to set the current read/write position to read or write at a certain position.
Syntax:
file.seek(offset[, from])
The <offset> argument represents the size of the displacement.
The <from> argument indicates the start point.
If from is 0, then the shift will start from the root level.
If from is 1, then the reference position will become the current position.
It from is 2, then the end of the file would serve as the reference position.
Assuming that file.txt contains ―Hello World‖ text, the following example demonstrates the seek()
method.
Example: seek()
1 file = open("D:\file.txt","r+")

2 file.seek(6,0)

3 lines = file.readlines()

4 for line in lines:

5 print(line)

6 file.close()

The output of the above example is "World".


Python File object methods

Function Description

<file.close()> Close the file. You must reopen it for additional access.

<file.flush()> Flush the internal buffer. It‘s same as the <stdio>‘s <fflush()> function.

<file.fileno()> Returns the descriptor of an integer file.

<file.isatty()> It returns true if file has a <tty> attached to it.

<file.next()> Returns the next line from the last offset.

<file.read(size)> Reads the given no. of bytes. It may read less if EOF is hit.

<file.readline(size)> It‘ll read an entire line from the file.

<file.readlines(size_hint)> It calls the <readline()> to read until EOF.

<file.seek(offset[, from])> Sets the file‘s current position.


<file.tell()> Returns the file‘s current position.

<file.truncate(size)> Truncates the file‘s size.

<file.write(string)> It writes a string to the file.

<file.writelines(sequence)> Writes a sequence of strings to the file.

Text books:

1. Wesley J. Chun, ―Core Python Applications Programming‖, 3rd Edition , Pearson Education, 2016

2. Lambert, Fundamentals of Python: First Programs with MindTap, 2nd 1st edition , Cengage
Learning publication

3. Charles Dierbach, ―Introduction to Computer Science using Python‖, Wiley, 2015

4. Jeeva Jose &P.SojanLal, ―Introduction to Computing and Problem Solving with PYTHON‖,
Khanna Publishers, New Delhi,

2016

5. Downey, A. et al., ―How to think like a Computer Scientist: Learning with Python‖, John Wiley,
2015

6. Mark Lutz, ―Learning Python‖, 5th edition, Orelly Publication, 2013, ISBN 978- 1449355739

7. John Zelle, ―Python Programming: An Introduction to Computer Science‖, Second edition, Course
Technology Cengage

Learning Publications, 2013, ISBN 978- 1590282410

8. Michel Dawson, ―Python Programming for Absolute Beginers‖ , Third Edition, Course Technology
Cengage Learning

Publications, 2013, ISBN 978-1435455009

9. David Beazley, Brian Jones., ―Python Cookbook‖, Third Edition, Orelly Publication, 2013, ISBN
978-1449340377

You might also like