How to Create and Delete Files/Directories in Python

Python provides several packages for working with the file system. They can be used for creating/deleting files and directories among other functionalities.

 

In this tutorial, we will learn how to create directories/files and delete files/directories in Python using the os, glob and shutil packages.

 

Create a File

To create a file in Python, use the open() function. The first argument is the name of the file and the second is the mode, which for writing/creating is w. Inside the with function write the content to the file using the write() method.

 

some_content = 'this is some content'

with open('test.txt', 'w') as f:
    f.write(some_content)

 

The key point about the above method is if a file with the same name doesn't exist in the directory it will create one.

 

To create the file in a different location pass the path before the file name. The example below will create a file called test.txt one directory above the location of the Python program by using .. (two dots).

 

with open('../test.txt', 'w') as f:
    f.write(some_content)

 

Read more about how the file system works in Linux.

 

Create Multiple Files

To create multiple files you could store the file names in a list and then use the open() function on each iteration of a for loop.

 

files = ['file1.txt', 'file2.txt', 'file3.txt']

for i in files:
    with open('test/'+ i, 'w') as f:
        f.write(some_content)

 

 

Import the os package

os is a native Python package that provides a collection of methods for getting information about the file system and performing operations on it. To use it, import it at the top of your program like this:

 

import os

 

Delete a File

To delete a file, use the os.remove() or os.unlink() method, supplying the path to the file as the first argument. On success, None will be returned.

 

file_path = '/Users/johnhoward/Dropbox/Python/Examples/test.txt'

result = os.remove(file_path)
print(result)
None

 

If the file is not found a FileNotFoundError error will be thrown or if the file is not a file a IsADirectoryError error will be thrown.

 

FileNotFoundError                         Traceback (most recent call last)
<ipython-input-4-0e29e912aa11> in <module>
      1 file_path = '/Users/johnhoward/Dropbox/Python/test'
      2 
----> 3 result = os.remove(file_path)

 

To catch errors we can put the delete operation inside a try and look for the OSError in the except.

 

file_path = 'blah.txt'

try:
    result = os.remove(file_path)
    print(result)
except OSError as e:
    print('Problem:', e)
Problem: [Errno 2] No such file or directory: 'blah.txt'

 

Delete Multiple Files That Match a Pattern

To delete multiple files in a directory that match a certain pattern import the glob package. Once glob is installed we can iterate through the matches returned from an expression inside the glob.glob() method and remove them.

 

import glob

for f in glob.glob('test/*.txt'):
    os.remove(f)

 

In the example above we are matching all the files with a .txt extension in the directory test and deleting them.

 

Create a Directory

To create a directory with Python use the os.mkdir() method, passing the name of the directory to create at the first argument of the method. On Sucess, None will be returned.

 

result = os.mkdir('new_dir')
print(result)
None

 

If a directory with the same name already exists, a FileExistsError error will be returned. Once again this could be put in a try except to catch errors.

 

try:
    result = os.mkdir('new_dir')
    print(result)
except OSError as e:
    print('Problem:', e)
Problem: [Errno 17] File exists: 'new_dir'

 

Create a Directory with Subdirectories

To make a directory with one or many subdirectories pass the path of directories into the os.makedirs() method.

 

path = 'test/sub_dir/new_dir/another'
os.makedirs(path)

 

Delete an Empty Directory

To delete an empty directory use the os.rmdir() method. If the directory contains files or subdirectories a “Directory not empty” OSError will be thrown.

 

path = 'test'

os.rmdir(path)

 

Delete a Directory and All Files and Directories Inside it

To delete a directory and all its content import the shutil package and pass the directory name into the shutil.rmtree() method.

 

import shutil

path = 'test'

shutil.rmtree(path)

 

Conclusion

You now know how to work with the file system using Python. With the os package the process of deleting/creating files and directories is clean and some of the methods have the same names as their terminal counterparts.

create remove file directory file system