File Handling in Python


Video Lecture


  • A file is a collection of bytes stored on a secondary storage device, which is generally a disk of some kind.

  • A file can be a text file or a binary file depending upon its contents.

  • Through file handling, one can perform operations like create, modify, delete etc on system files.

  • File I/O can be performed on a character by character basis, a line by line basis, a record by record basis or a chunk by chunk basis.

  • In Python, there is no need for importing external library to read and write files. Python provides built-in functions for creating, writing, and reading files.


File Operations :

In Python, we can perform operations in following order:
  1. Open / Create a new file
  2. Reading from and writing to a file.
  3. Close a file

Opening / Create a File in Python :

Before performing any operations(read/write), first we need to open the file. Python provides a built-in function open() to open a file. This function returns a file object, which we use for read or write operations onto the file accordingly.

Syntax :

                    
f = open("filepath", "opening_mode")
                

Example :

                    
f = open("test.txt") # open file in current directory
f = open("C:/Python38/test.txt") # specifying full path of file
                

There are two ways to specify the file path, first by writing on name of the file, in that case file will be search at current working directory, and second way is by specifying full path of file.

File Opening Modes

When we open a file, we can specify the opening mode also. Opening mode means which operation we are going to perform onto the file. There are following modes

ModeDescriptionWhat if file doesn't exist
rOpen text file for reading.The stream is positioned at the beginning of the file.If file doesn't exist, then open() returns None.
wOpen text file for writing.If file exist, it truncate the contents.If doesn't exist, then open() creates the file.
aOpen text file for appending (writing at end of file).The file is created if it does not exist. The stream is positioned at the end of the file.
r+Open text file for reading and writing.If file doesn't exist, then open() returns None.
w+Open text file for writing and reading.If file exist, it truncate the contents.If doesn't exist, then open() creates the file.
a+Open for reading and appending (writing at end of file). The file is created if it does not exist. The initial file position for reading is at the beginning of the file, but output is always appended to the end of the file.

If we don't specify any mode in open() functions as second argument, by default it is r mode.

Example :

                    
f = open("test.txt")      # opening file in read mode
f = open("test.txt",'w')  # opening file in write mode
                

Reading Data from a file in Python :

To perform the reading operation onto the file, first we must to open a file in reading mode.

Python provides the following functions to perform the reading operation onto the file.

MethodDescription
read(n)read the specified number of data.
readline()this reads data line by line.
readlines()this reads and return the list of strings of lines.

read() method :

read() method will read the specified number of data from file, if we don't specify the number then it will read all the data in one go and returns string.


file: test.txt
This is my file.
This is example of reading operations.
We can perform the reading operations in different ways.                    
                

Let's take that we want to read the data from test.txt, and file looks like as above


file: myscript.py
                    
f = open("test.txt") # opening in read mode
data = f.read(6)     # read first 5 data
print(data)
# [OUTPUT]
#This i

data = f.read(4)    # read next 4 data
print(data)
# [OUTPUT]
#s my

data = f.read() # read remaining all data till end of file
print(data)
# [OUTPUT]
''' file.
This is example of reading operations.
We can perform the reading operations in different ways.'''

data = f.read() #this will return empty string
print(data)
# [OUTPUT]
''
                

As we can see when all the data has been read from the file, read() method returns empty string because it reaches at the end of file(EOF). We can read the by using the loop also as

                    
f = open("test.txt")
data = f.read(10)
while len(data)>0:
    print(data, end='')
    data = f.read(10)
                
OUTPUT
                    
This is my file.
This is example of reading operations.
We can perform the reading operations in different ways. 
                

readline() method

The readline() method reads the data from file line by line. It reads one line at a time and returns the data.

In readline(), we can also specify the limit of data to be read by the function as we did in read() method.

                    
f = open("test.txt")
data  = f.readline() # read the first line
print(data, end='')

data  = f.readline() # read the next line
print(data, end='')
                
OUTPUT
                    
This is my file.
This is example of reading operations.
                

As we can see we are getting the data line by line as output. We called printline() method two times that's why we are getting two lines of file as output.

Similar to the read() method, when readline() method will reach at the end of file, it also returns an empty string.

                    
f = open("abc.txt","r")
data = f.readline()
while len(data)>0:
    print(data, end='')
    data = f.readline()
                
OUTPUT
                    
This is my file.
This is example of reading operations.
We can perform the reading operations in different ways.
                

readlines() method

The readlines() method reads all the data line by line from a file and stores into list and return it.

                    
f = open("abc.txt","r")
data = f.readlines()
print(data)
                
OUTPUT
                    
['This is my file.\n', 'This is example of reading operations.\n', 
'We can perform the reading operations in different ways.  ']
                

As we can see the variable data is holding all the data from file lie by line as list.


Writing Data to a File in Python :

To perform writing operation onto the file, first we need to open the file in write(w) or append(a) mode.

Both modes will create a new file at specified path, if file doesn't exist.

If the file exists then, w mode will truncate all the data from file and gives us blank file to write the data from beginning, where a mode will not truncate the previous data,It starts appending the new data at the end of file.

                    
f = open("mydata.txt","w")
f.write("This is first statement\n")
f.write("This is second statement\n")
f.write("This is third statement\n")

                

Above code will create a new file with the name mydata.txt at the current location, if file doesn't exist, else it will open a blank file to write.

We use a write() method to perform writing operation on to the file.

We must include the newline characters ourselves to change the lines.


Close the File :

It is a good practice, the file (both text or binary) should be closed after reading/writing operation completed.

The close() function is used for closing opened files.

                    
f = open("mydata.txt","w")
f.write("This is first statement\n")
f.write("This is second statement\n")
f.write("This is third statement\n")
f.close()
                

Opening a file using 'with'

Python provides a very clean syntax and exceptions handling when we are working with code.

This syntax/method will close automatically any opened file after the operation(reading/writing) is done, so this code is auto-cleanup. We don't need to close the file.

                    
with open("abc.txt") as f:
    data = f.read()
    print(data)
                
OUTPUT
                    
This is my file.
This is example of reading operations.
We can perform the reading operations in different ways.
                

Next chapter is Anonymous Function






 
Udemy APAC

Udemy APAC




Online Live Training

We provide online live training on a wide range of technologies for working professionals from Corporate. We also provide training for students from all streams such as Computer Science, Information Technology, Electrical and Mechanical Engineering, MCA, BCA.

Courses Offered :

  • C Programming
  • C++ Programming
  • Data Structure
  • Core Java
  • Python
  • Java Script
  • Advance Java (J2EE)
  • Hibernate
  • Spring
  • Spring Boot
  • Data Science
  • JUnit
  • TestNg
  • Git
  • Maven
  • Automation Testing - Selenium
  • API Testing

NOTE: The training is delivered in full during weekends and during the evenings during the week, depending on the schedule.

If you have any requirements, please send them to prowessapps.in@gmail.com or info@prowessapps.in


Projects For Students

Students can contact us for their projects on different technologies Core Java, Advance Java, Android etc.

Students can mail requirement at info@prowessapps.in


CONTACT DETAILS

info@prowessapps.in
(8AM to 10PM):

+91-8527238801 , +91-9451396824

© 2017, prowessapps.in, All rights reserved