Open In Colab

Working with Files in Python

Python's Built-in Functions

  • Use the built-in open( ) function to open a file. The open() function returns a file object, which has a read() method for reading the content of the file.
  • Close the file when you are finish with it.
  • There are four different methods for opening a file.
  • "r" - Default value. Opens a file for reading.
  • "a" - Opens a file for appending, creates the file if it does not exist.
  • "w" - Opens a file for writing, creates the file if it does not exist.
  • "x" - Creates the specified file, returns an error if the file exists.
  • Use os.remove( ) function to delete a file.
  • Use os.rmdir( ) function to delete an entire folder.
In [1]:
from google.colab import drive
drive.mount('/content/drive')
Drive already mounted at /content/drive; to attempt to forcibly remount, call drive.mount("/content/drive", force_remount=True).
In [2]:
f = open('/content/drive/My Drive/fibonacci.py', 'r')
print(f.read()) 
def fib(m):
    a, b = 0, 1
    for i in range(m):
        print(a)
        a, b = b, a+b

def fi(n):
    L = [0]
    a, b = 0, 1
    for i in range(n-1):
        a, b = b, a+b
        L.append(a)
    return L

In [3]:
f.close()

The os Module and other Modules

  • The os module contains functions to get information on local directories, files, processes, and environment variables.
  • os.getcwd( ): gets current working directory
  • os.chdir( ): changes the current working directory
  • os.path.join( ): adds an extra slash to the pathname before joining it to the filename.
  • os.path.split( ): splits full pathnames, directory names, and filenames into their constituent parts.
  • os.path.splitext( ): splits a filename and returns a tuple containing the f_name and the file extension.
  • os.listdir( ): lists all files and subdirectories in the directory.
  • os.path.isfile( ): only lists files and not subdirectories.
  • os.path.isdir( ): only lists subdirectories and not files.
  • os.mkdir( ): creates a single subdirectory.
  • os.mkdirs( ): creates directory trees.
  • os.remove( ): deletes a file and does not delete folders.
  • os.rmdir( ): deletes a single folder.
  • shutil.copy(src, dst): copys the file scr to the directory dst.
  • shutil.move(src, dst): moves src to dst.
  • shutil.make_archive(base_name, format, root_dir): creates an archive.
  • shutil.unmake)archive
In [4]:
import os
print(os.getcwd())
/content
In [5]:
os.chdir('/content/drive/My Drive')
In [6]:
pwd
Out[6]:
'/content/drive/My Drive'
In [7]:
print(os.path.join('/content/drive/My Drive', 'fibonacci.py'))
/content/drive/My Drive/fibonacci.py
In [8]:
path1 = '/content/drive/My Drive/fibonacci.py'
os.path.split(path1)
Out[8]:
('/content/drive/My Drive', 'fibonacci.py')
In [9]:
(dirname, filename) = os.path.split('/content/drive/My Drive/fibonacci.py')
print(dirname)
print(filename)
/content/drive/My Drive
fibonacci.py
In [10]:
(f_name, extension) = os.path.splitext('/content/drive/My Drive/breccia.zip')
print(f_name)
print(extension)
/content/drive/My Drive/breccia
.zip
In [11]:
os.listdir('/content/drive/My Drive')
Out[11]:
['Colab Notebooks',
 'Data',
 'breccia.zip',
 'w_2020',
 'breccia',
 'breccia_jpg',
 'breccia_crop',
 'fibonacci.py',
 'test.txt.zip']
In [12]:
# Listing all files in a directory 
path2 = '/content/drive/My Drive'
for item in os.listdir(path2):
    if os.path.isfile(os.path.join(path2,item)):
        print(item)
breccia.zip
fibonacci.py
test.txt.zip
In [13]:
# Listing all subdirectories in a directory
path3 = '/content/drive/My Drive'
for entry in os.listdir(path3):
    if os.path.isdir(os.path.join(path3, entry)):
        print(entry)
Colab Notebooks
Data
w_2020
breccia
breccia_jpg
breccia_crop
In [14]:
os.chdir('/content/drive/My Drive')
In [15]:
pwd
Out[15]:
'/content/drive/My Drive'
In [16]:
os.mkdir ('aa')
In [17]:
os.makedirs('a/b/c')
In [18]:
os.listdir('/content/drive/My Drive')
Out[18]:
['Colab Notebooks',
 'Data',
 'breccia.zip',
 'w_2020',
 'breccia',
 'breccia_jpg',
 'breccia_crop',
 'fibonacci.py',
 'test.txt.zip',
 'aa',
 'a']
In [19]:
# Finding all files in a directory with .py file extension.
for f_name in os.listdir('/content/drive/My Drive'):
    if f_name.endswith('.py'):
        print(f_name)
fibonacci.py
In [20]:
f1 = open('/content/drive/My Drive/a/f1.txt', 'w')
In [21]:
print(f1)
<_io.TextIOWrapper name='/content/drive/My Drive/a/f1.txt' mode='w' encoding='UTF-8'>
In [22]:
os.listdir('/content/drive/My Drive/a')
Out[22]:
['b', 'f1.txt']
In [23]:
os.remove('/content/drive/My Drive/a/f1.txt')
In [24]:
os.listdir('/content/drive/My Drive/a')
Out[24]:
['b']
In [25]:
os.rmdir('/content/drive/My Drive/a/b/c')
In [26]:
os.listdir('/content/drive/My Drive/a/b')
Out[26]:
[]
In [27]:
import shutil
shutil.copy('/content/drive/My Drive/fibonacci.py', '/content/drive/My Drive/aa')
Out[27]:
'/content/drive/My Drive/aa/fibonacci.py'
In [28]:
os.listdir('/content/drive/My Drive/aa')
Out[28]:
['fibonacci.py']
In [29]:
shutil.move('/content/drive/My Drive/a/b', '/content/drive/My Drive/aa')
Out[29]:
'/content/drive/My Drive/aa/b'
In [30]:
os.listdir('/content/drive/My Drive/aa')
Out[30]:
['b', 'fibonacci.py']
In [31]:
shutil.unpack_archive('/content/drive/My Drive/test.txt.zip', '/content/drive/My Drive')
In [32]:
os.listdir('/content/drive/My Drive')
Out[32]:
['Colab Notebooks',
 'Data',
 'breccia.zip',
 'w_2020',
 'breccia',
 'breccia_jpg',
 'breccia_crop',
 'fibonacci.py',
 'test.txt.zip',
 'aa',
 'a',
 'test.txt',
 '__MACOSX']