Learning Python - Basic File Operations

In this article we will discuss basic file operations in Python, file types supported in Python and file handling details.

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 external library 🙂
  3. Close the file
Lets explore each operations,
 

Open a file

  1. In python we open file using open() method
  2. open() returns file object
  3. syntax: file = open(filename, mode) where,
  4. filename: name of the file if file is in current directory. Or absolute path of file
  5. mode: Optional parameter. Possible values for mode are
Mode Details
r read. This is default mode in case we didn’t specified mode parameter
w write. Existing content will be overwritten. New file will be created if specified file does not exists
a append the content to existing content in a given file. New file will be created if specified file does not exists
r+ Opens the file for both operations – reading and writing
x create. Creates the specified file either in current directory or on specified path. If specified file is already exists then returns an error
 
Along with mode parameter, we can also specify parameter for 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 file, we need to open file in write mode, otherwise 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 existing file  
  4. file.write(“Writing to file – This is again first line since it will overwrite the content of existing file”) 
Append the new content to existing content of file,
  1. #to append to the file, we need to open file in append mode  
  2. file = open(r”c:\Prasham\Blogs\Python\FileOperations\pythonfileoperations.txt”, ‘a’)
  3. file.write(“Writing to file – This is 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”) 
These are the basic file operations discussed in this article, in next article we will discuss some more file handling details :)