Python OS Module – Opening and reading files

Welcome back, everyone. In this lecture, we’re going to be focusing on built-in modules that relate to Python OS Module – opening and reading files and folders on your computer.

Pythons OS module allows us to easily navigate files and directories on the computer and then perform actions on them, such as moving them or deleting them.

Let’s go ahead and explore these Python OS module and get started.

First we have to know how to read file manually one by one in python.

Let’ we have a file named demo.txt in the current directory. If you don’t, just create one, and then fill with few lines and save it. I hope you are ready to open the saved file.

myfile = open("demo.txt")
txt = myfile.read()
print(txt)
myfile.close()

Or, You can also do with this:

myfile = open("demo.txt")
print(myfile.read())
myfile.close()

So far we’ve discussed how to open files manually, one by one. Let’s explore how we can open files programmatically.

Getting Directories

Python has a built-in os module that allows us to use operating system dependent functionality.

You can get the current directory:

import os
os.getcwd()

Listing Files in a Directory

You can also use the os module to list directories.

os.listdir()

If I run this command in my Jupiter notebook, Output will be:

['.anaconda',
 '.astropy',
 '.bash_history',
 '.bash_profile',
 '.conda',
 '.condarc',
 '.config',
 '.dbshell',
 '.idlerc',
 '.ipynb_checkpoints',
 '.ipython',
 '.jupyter',
 '.matplotlib',
 '.mongorc.js',
 '.octave_hist',
 '.PyCharmCE2019.2',
 '.spyder-py3',
 'Application Data',
 'Blog.ipynb',
 'Contacts',
 'Cookies',
 'data',
 'Desktop',
 'Documents',
 'Downloads',
 'Favorites',
 'IBA_IOAPDATA',
 'IntelGraphicsProfiles',
 'Links',
 'Local Settings',
 'MicrosoftEdgeBackups',
 'mod.ipynb',
 'mynotebook.ipynb',
 'NetHood',
 'NTUSER.DAT',
 'ntuser.dat.LOG1',
 'ntuser.dat.LOG2',
 'NTUSER.DAT{53b39e88-18c4-11ea-a811-000d3aa4692b}.TM.blf',
 'NTUSER.DAT{53b39e88-18c4-11ea-a811-000d3aa4692b}.TMContainer00000000000000000001.regtrans-ms',
 'NTUSER.DAT{53b39e88-18c4-11ea-a811-000d3aa4692b}.TMContainer00000000000000000002.regtrans-ms',
 'ntuser.ini',
 'OneDrive',
 'Pictures',
 'PrintHood',
 'PycharmProjects',
 'Recent',
 'Saved Games',
 'Templates',
 'tic tak toi.ipynb',
 'Untitled1.ipynb',
 'Untitled2.ipynb',
 'Untitled3.ipynb',
 'Untitled4.ipynb',
 'Untitled5.ipynb',
 'Untitled6.ipynb']

You can also pass the directory path in this command like:

python os module

Moving Files

You can use the built-in shutil module to move files to different locations. Always Keep in mind, there are permission restrictions, for example, if you are logged in a User A, you won’t be able to make changes to the top-level Users folder without the proper permissions, more info

import shutil
shutil.move('demo.txt','C:\\Users\\diksh')
Output: 'C:\\Users\\diksh\\demo.txt'


Deleting Files

NOTE: The os module provides 3 methods for deleting files:

  • os.unlink(path) which deletes a file at the path you provide
  • os.rmdir(path) which deletes a folder (folder must be empty) at the path your provide
  • shutil.rmtree(path) this is the most dangerous, as it will remove all files and folders contained in the path. All of these methods can not be reversed! This means if you make a mistake you won’t be able to recover the file.

Different commands of Python OS Module

  • os.name: This function returns the name of the operating system dependent module imported. Let us have the few names that have currently been registered: ‘java’ and ‘riscos’. example:
import os 
print(os.name) 
Output: java
  • os.read: this function is used for reading files.
  • os.getcwd: it returns the (CWD) current Working Directory of the file used to execute the code, it can vary from system to system.
  • os.error: All functions in this module raise OSError in the case of invalid file names and paths, or other arguments that have the correct type. But they are not accepted by the operating system. The python os.error is an alias for built-in OSError exception.
import os 
try: 
    # If the file does not exist, 
then it would throw an IOError 
    filename = 'file.txt'
    a = open(filename, 'rU') 
    text = a.read() 
    a.close() 
  
# Control jumps directly to here if any of the above lines throws IOError.     
except IOError: 
  
    # print(os.error) will <class 'OSError'> 
    print('Problem reading: ' + filename)
  • os.popen(): This method is used to open a pipe to or from command. The returned value can be read or written depending upon whether the mode is ‘r’(read) or ‘w’(write). Syntax:
 os.popen(command[, mode[, bufsize]])

The Parameters – mode & bufsize are not necessary parameters, if we does not provide value of both, the default ‘r’ is taken for the mode.

  • os.close(): Using this we can close the already opened file. A file opened using open() command, it can be closed by close() only. But in case of a file which is opened by os.popen(), that can be closed with close() or os.close(). If we try closing a file opened with open(), using os.close(), Python would throw the TypeError.
import os 
f = "file.txt"
file1 = open(f, 'r') 
text = file1.read() 
print(text) 
os.close(file1) 

Output will be:

python os module
  •  os.rename(): A file A.txt can be renamed to B.txt, using the function os.rename(). The name of the file changes only if, the file exists, and also the user has privilege permission to change the file name. Example: I don’t save the GFG.txt in my system, below mentioned code will throw an error.
import os 
f = "GFG.txt"
os.rename(f,'New.txt') 
os.rename(f,'New.txt')

Output;

python os module

Related Topics:


All right. So that’s it for this topic, we have discussed the Python OS module with suitable examples. I hope these can really help you and I will see you at the next topic.

5 thoughts on “Python OS Module – Opening and reading files

Leave a Reply

Your email address will not be published. Required fields are marked *