The os module and file handling in python

Python has a wide variety of modules on its standard library that are used for different kinds of purposes in programming. One of the important modules among python's standard library is the os module which deals with the operating system of your machine. It has a lot of functions related to the file system which is able to perform most of the operations related to files. So let us check each function one by one.

First of all, we need to import os the module from the library

>>> import os
>>>

The os.path.join() method

import os
 
document_folder = "C:\\Users\\sidharth\\documents"
file = "document.txt"
path = os.path.join( document_folder, file )

print("Path of the file:"+ path)

output:
>>> Path of the file: C:\Users\sidharth\documents\document.txt
The os.path.join( ) function is helpful when we need to create strings for file names. It joins the file name at the end of the folder path. In the above case, the file document.txt is joined to document_folder at the end and returns the entire string as output.

The os.getcwd() and os.chdir() methods

C:\Users\sidharth> python
Python 3.8.3 [GCC 4.8.2] on win32  
Type "help","copyright","credits"or"license" for more information.
>>>
>>> import os
>>> os.getcwd()
'C:\\Users\\sidharth'
>>>
>>> os.chdir("E:\Allfiles")
>>>
>>> os.getcwd()
'E:\\Allfiles'
>>>
os.getcwd( ) function returns the current working directory you are in, It is short for getting Current Working Directory. This may be quite useful when we are working with a large number of codes with files. On the other hand, os.chdir( path ) is a function to change the current working directory, In the above case, the current working directory "C:\Users\sidharth" changes when we call the os.chdir function by specifying the name of the new directory as an argument.  

The os.makedirs() method

C:\Users\sidharth> python
Python 3.8.3 (default, June 19 2021, 09:25:04)
[GCC 4.8.2] on win32
Type "help", "copyright", "credits"or"license" for more information.
>>>
>>> import os
>>> os.makedirs("E:\\Allfiles\\test\\test-dir")
>>>

The os module and file handling in python

A new folder is created when we run the function os.makedirs(path). As you can see the test-dir folder is created in the specified path. os.makedirs is basically a function to create a new directory
.

The os.listdir() method

The os module and file handling in python
C:\Users\sidharth\documents
import os
 
path = "C://Users//sidharth//documents"
os.listdir( path )

output:
>>> ['document1.txt', 'document2.txt']
The os.listdir( path ) function creates a list of all the files in a particular directory like the one above. We have two document files document1 and document2 which are in the Documents folder returned as a string inside a list when we run os.listdir function. We can access all the files in a folder by looping through the list.

 The os.path.abspath(), os.path.isabs(), os.path.relpath() and os.path.getsize() functions

C:\Users\sidharth> python
Python 3.8.3 (default, June 19 2021, 09:25:04)
[GCC 4.8.2] on win32
Type "help", "copyright", "credits" or"license" for more information.
>>>
>>> import os
>>>
>>> os.path.abspath('.')
'C:\\Users\\sidharth'
>>>
>>> os.path.isabs('.')
False
>>>
>>> os.path.isabs('C:\\Users\\sidharth')
True
>>> os.path.getsize('C:\\Users\\sidharth')
12288
  • os.path.abspath( path ) will return a string of the absolute path of the argument. This is an easy method to convert a relative path into an absolute one.
  • os.path.isabs( path ) will return True when the argument is an absolute path and False if the path is relative.
  • os.path.relpath( path, start ) will return a string of relative path from start to the path provided. 
  • os.path.getsize( path ) will return the size in bytes of the file in the path argument.

Opening files with open() method

The os module and file handling in python

with open("greetings.txt") as doc_file:
    greeting_file = doc_file.read()
    print(greeting_file)

output:
>>> Hi there, welcome to pycodemates

This program prints the content written in the greetings.txt file. The open( path/filename ) function returns a File object and read( ) function helps to fetch the contents in the file object and prints them in the console.

The read(), readlines(), and write() methods

  • Once you have the File object you can access the method read( ) and write( ). If you want to read the entire contents of a file as a string value, you can use the File objects method read( ).
  • If you want to create a new file or to write something into the existing content you can use the write( ) method.
  • When you want to get a list of string values from the file, one string for each line of text you can use the readlines( ) method. 
with open("greetings.txt","w") as doc_file:
    greeting_file = doc_file.write("This is a new file.")
    print(greeting_file)

The os module and file handling in python

The open( ) method with the arguments file name and  "w" ( write mode ) tells python that we need to write a new word or sentence in a new file, This cannot be used when we need to write something to an existing file when we do so, the entire data in the file is replaced by the argument we passed. In that case, we need to use the "a" ( append mode ).  

with open("greetings.txt","a") as doc_file:
    greeting_file = doc_file.write(
                    "This is written to an existing file.")
    print(greeting_file)

The os module and file handling in python


Here the new string is added to the file greetings.txt
https://www.linkedin.com/in/sidharth-gn-4ab311208/