Learning Python - Basic File Operations

Introduction

 
In the last three articles "Learning Python - Introduction To Python", "Learning Python - Installation Of Python On Windows 10", "Learning Python - First Python Program With Visual Studio Code" we discussed the introduction to Python, why to learn Python, how to install Python on Windows 10, first python program using Visual Studio Code IDE.
 
In this article, we will discuss basic file operations in Python.  How to do file handling in Python and file operation methods.
 
There are two types of file supported in Python,
  1. Text files
  2. Binary files
 In Python, the following is the order of file operations,
  1. Open a file
  2. Read or write (perform operations) – Interestingly for reading and writing file in Python we don’t need to import an external library 🙂.
  3. Close the file
Let's explore each operation,
 

Open a file

  1. In python, we open the file using open() method
  2. open() returns file object
  3. syntax: file = open(filename, mode) where,
  4. filename: Name of the file if the file is in the current directory. Or the absolute path of the file
  5. mode: Optional parameter. Possible values for mode are
Mode Details
r read. This is the default mode in case we didn’t specified mode parameter
w write. Existing content will be overwritten. The new file will be created if a specified file does not exist
a append the content to existing content in a given file. The new file will be created if a specified file does not exist
r+ Opens the file for both operations – reading and writing
x create. Creates the specified file either in the current directory or on a specified path. If a specified file already exists then returns an error
 
Along with the mode parameter, we can also specify parameter for the file type, whether the file should be treated as a text or a binary file by specifying “t” or “b”
 
Opening the file,
  1. #Following open() method will open file in read mode and returns file object  
  2. file = open(“c:\Prasham\Blogs\Python\pythonfileoperations.txt”, ‘rt’) 

Reading the file

 
There are multiple ways to read the file.
 
Reading the complete file, as one string,
  1. #read complete file – return one big string  
  2. print(file.read()) 
Reading file line by line,
  1. #This will print every line one by one in the file  
  2. for each in file:  
  3.     print (each)  
  4. #OR  
  5. data = file.readlines()  
  6. for line in data:  
  7.     print(line) 
Read single line at a time,
  1. #reading one line at a time.  
  2. #reads the file till new line  
  3. print(file.readline()) 

Writing to the file

 
To write into a file, we need to open the file in write mode, otherwise, an exception will be there – io.UnsupportedOperation: not writable
 
Overwriting the existing file,
  1. #open file in write mode  
  2. file = open(“c:\Prasham\Blogs\Python\FileOperations\pythonfileoperations.txt”, ‘w’)  
  3. #By default it overwrites to the existing file  
  4. file.write(“Writing to file – This is again the first line since it will overwrite the content of the existing file”) 
Append the new content to existing content of the file,
  1. #to append to the file, we need to open the file in append mode  
  2. file = open(r”c:\Prasham\Blogs\Python\FileOperations\pythonfileoperations.txt”, ‘a’)
  3. file.write(“Writing to file – This is the second line”) 
Writing multiple lines to file,
  1. #writing multiple lines to file  
  2. file = open(“c:\Prasham\Blogs\Python\FileOperations\pythonfileoperations.txt”, ‘a’)  
  3. #create array of lines  
  4. lines_of_text = [“a line of text”, “another line of text”, “a third line”]  
  5. file.writelines(lines_of_text)  
  6. file.close() 
Crating a new file,
  1. #creating a file. Returns error if file exists exception: FileExistsError  
  2. file = open(r”c:\Prasham\Blogs\Python\FileOperations\pythonfileoperations_new.txt”, ‘x’) 

Deleting the file

 
To delete file, we import os module and use remove()
  1. mport os  
  2. os.remove(r”c:\Prasham\Blogs\Python\FileOperations\pythonfileoperations_new.txt”)  
  3.   
  4. #We can also check if file exists or not  
  5. #check if file exists  
  6. if os.path.exists(“demofile.txt”):  
  7. os.remove(“demofile.txt”)  
  8. else:  
  9. print(“The file does not exist”) 

Summary

 
These are the basic file operations discussed in this article, in next article we will discuss some more file handling details :)


Similar Articles