Python Directory & File Management – A Quick and Easy Tutorial

Keeping you updated with latest technology trends, Join DataFlair on Telegram

1. Python Directory Tutorial

So far, we’ve mostly only seen the computational capabilities of Python. Today, we’ll talk about how we can use it to handle Python directory. After this tutorial, you’ll be able to create, rename, list files in a directory in Python, and work with the Python Directory.

In a computer system, files are organized into directories. These may contain subdirectories and files. Indeed, this makes a vital part of a user-friendly UI. But don’t be confused; a dictionary is simply what you call a folder.

In this Python Directory tutorial, we will import the OS module to be able to access the methods we will apply.

>>> import os
Python Directory

Introduction to Python Directory

2. Getting Current Python Directory

To find out which directory in python you are currently in, use the getcwd() method.

>>> os.getcwd()


Cwd is for current working directory in python. This returns the path of the current python directory as a string in Python. To get it as a bytes object, we use the method getcwdb().

>>> os.getcwdb()


Here, we get two backslashes instead of one. This is because the first one is to escape the second one since this is a string object.

>>> type(os.getcwd())
<class 'str'>

To render it properly, use the Python method with the print statement.

>>> print(os.getcwd())


3. Changing Current Python Directory

To change our current working directories in python, we use the chdir() method. This takes one argument- the path to the directory to which to change.

>>> os.chdir('C:\Users\lifei')

SyntaxError: (unicode error) ‘unicodeescape’ code can’t decode bytes in position 2-3: truncated \UXXXXXXXX escape

But remember that when using backward slashes, it is recommended to escape the backward slashes to avoid a problem.

>>> os.chdir('C:\\Users\\lifei')
>>> os.getcwd()


When you restart the shell, we get back to the default working python directory.

>>> os.chdir('C:\\Users\\lifei')
>>> os.getcwd()


You can also use forward slashes for the path. This way, you don’t have to use backward slashes to escape.

>>> os.chdir('C:/Users/lifei')
>>> os.getcwd()


Finally, you can also use double quotes.

>>> os.chdir("C:\\Users\\lifei")

4. Python List Directories and Files

To get the contents of a directory into a python list, we use the listdir() method.

>>> os.listdir()

[‘.atom’, ‘.eclipse’, ‘.idlerc’, ‘.p2’, ‘.tooling’, ‘.vscode’, ‘3D Objects’, ‘afiedt.buf’, ‘AppData’, ‘Application Data’, ‘Contacts’, ‘Cookies’, ‘Desktop’, ‘Documents’, ‘Downloads’, ‘Dropbox’, ‘eclipse’, ‘eclipse-workspace’, ‘eclipse-workspace-C++’, ‘eclipse-workspace-EE’, ‘Favorites’, ‘iCloudDrive’, ‘IntelGraphicsProfiles’, ‘Links’, ‘Local Settings’, ‘MicrosoftEdgeBackups’, ‘Music’, ‘My Documents’, ‘NetHood’, ‘NTUSER.DAT’, ‘ntuser.dat.LOG1’, ‘ntuser.dat.LOG2’, ‘NTUSER.DAT{03a9cc49-f0a2-11e7-904c-d9989e93b548}.TM.blf’, ‘NTUSER.DAT{03a9cc49-f0a2-11e7-904c-d9989e93b548}.TMContainer00000000000000000001.regtrans-ms’, ‘NTUSER.DAT{03a9cc49-f0a2-11e7-904c-

d9989e93b548}.TMContainer00000000000000000002.regtrans-ms’, ‘ntuser.ini’, ‘OneDrive’, ‘Oracle’, ‘Pictures’, ‘PrintHood’, ‘Recent’, ‘Roaming’, ‘Saved Games’, ‘Searches’, ‘SendTo’, ‘Start Menu’, ‘Templates’, ‘Videos’, ‘workspace’]

Note that this includes the hidden and system files as well.

>>> os.chdir("C:\\Users\\lifei\\Desktop")
>>> os.listdir()

[‘Adobe Photoshop CS2.lnk’, ‘Atom.lnk’, ‘Burn Book.txt’, ‘desktop.ini’, ‘Documents’, ‘Eclipse Cpp Oxygen.lnk’, ‘Eclipse Java Oxygen.lnk’, ‘Eclipse Jee Oxygen.lnk’, ‘For the book.txt’, ‘Items for trip.txt’, ‘Papers’, ‘Remember to remember.txt’, ‘Sweet anticipation.png’, ‘Today.txt’, ‘topics.txt’, ‘unnamed.jpg’]

This shows us the contents on the desktop. This was about Python List directory.

5. How to Create Python Directory?

We can also create new python directories with the mkdir() method. It takes one argument, that is, the path of the new python directory to create.

>>> os.mkdir('Christmas Photos')
>>> os.listdir()

[‘Adobe Photoshop CS2.lnk’, ‘Atom.lnk’, ‘Burn Book.txt’, ‘Christmas Photos’, ‘desktop.ini’, ‘Documents’, ‘Eclipse Cpp Oxygen.lnk’, ‘Eclipse Java Oxygen.lnk’, ‘Eclipse Jee Oxygen.lnk’, ‘For the book.txt’, ‘Items for trip.txt’, ‘Papers’, ‘Remember to remember.txt’, ‘Sweet anticipation.png’, ‘Today.txt’, ‘topics.txt’, ‘unnamed.jpg’]

Here, we supplied the name of the python directory to create. We can also create a directory in a directory other than the current working directory in python. For this, you must specify the full path.

6. How to Rename Python Directory?

To rename directories in python, we use the rename() method. It takes two arguments- the python directory to rename, and the new name for it.

>>> os.rename('Christmas Photos','Christmas 2017')
>>> os.listdir()

[‘Adobe Photoshop CS2.lnk’, ‘Atom.lnk’, ‘Burn Book.txt’, ‘Christmas 2017’, ‘desktop.ini’, ‘Documents’, ‘Eclipse Cpp Oxygen.lnk’, ‘Eclipse Java Oxygen.lnk’, ‘Eclipse Jee Oxygen.lnk’, ‘For the book.txt’, ‘Items for trip.txt’, ‘Papers’, ‘Remember to remember.txt’, ‘Sweet anticipation.png’, ‘Today.txt’, ‘topics.txt’, ‘unnamed.jpg’]

7. How to Remove Python Directory/File?

We made a file named ‘Readme.txt’ inside our folder Christmas 2017. To delete this file, we use the method remove().

>>> os.chdir('C:\\Users\\lifei\\Desktop\\Christmas 2017')
>>> os.listdir()

To remove a python directory, we use the rmdir() method. But for this, the directory must be empty. So we’ll add Readme.txt again to check if we’re able to delete Christmas 2017.

>>> os.rmdir('Christmas 2017')
Traceback (most recent call last):
File "<pyshell#412>", line 1, in <module>
os.rmdir('Christmas 2017')

OSError: [WinError 145] The directory is not empty: ‘Christmas 2017’

As you can see, it raised a python exception called OSError. So let’s first remove the file and then delete the python directory.

>>> os.remove('C:\\Users\\lifei\\Desktop\\Christmas 2017\\Readme.txt')
>>> os.rmdir('Christmas 2017')
>>> os.listdir()

[‘Adobe Photoshop CS2.lnk’, ‘Atom.lnk’, ‘Burn Book.txt’, ‘desktop.ini’, ‘Documents’, ‘Eclipse Cpp Oxygen.lnk’, ‘Eclipse Java Oxygen.lnk’, ‘Eclipse Jee Oxygen.lnk’, ‘For the book.txt’, ‘Items for trip.txt’, ‘Papers’, ‘Remember to remember.txt’, ‘Sweet anticipation.png’, ‘Today.txt’, ‘topics.txt’, ‘unnamed.jpg’]

Also, learn how to do exception handling in python.

8. Joining and Splitting Path

We must use platform-independent file and directory in python paths, so our program runs on every platform. We use the submodule os.path for this.
join() in python joins path components and returns a path as a string. It adds appropriate separators (\ for Windows and / for Unix)

>>> os.path.join('C:','Users','lifei','Desktop')

Conversely, split() splits the path into components, removing the separator.

>>> os.path.split('C:Users\\lifei\\Desktop')

(‘C:Users\\lifei’, ‘Desktop’)

9. Checking if Python Directory Exists

It is possible to check whether a path exists. We use the exists() function for this. Also, this is in the os.path submodule.

>>> os.path.exists('C:\\Users\\lifei\\Desktop')


>>> os.path.exists('C:\\Users\\lifei\\Desktop\\Myfolder')


>>> os.path.exists('C:\\Users\\lifei\\Desktop\\topics.txt')

Then, to check whether that path leads us to a directory, we use the isdir() function.

>>> os.path.isdir('C:\\Users\\lifei\\Desktop')


>>> os.path.isdir('C:\\Users\\lifei\\Desktop\\topics.txt')


10. Recursively Traversing a Directory in Python

The walk() function lets us recursively traverse a directory. This means that it returns the roots, subdirectories, and files in a directory. You can traverse it using for loops in Python.

>>> for roots,dirs,files in os.walk('C:\\Users\\lifei\\Desktop\\Papers'):

C:\Users\lifei\Desktop\Papers 1 29
C:\Users\lifei\Desktop\Papers\Newfolder 0 1

>> for roots,dirs,files in os.walk('C:\\Users\\lifei\\Desktop\\Papers'):               

C:\Users\lifei\Desktop\Papers [‘Newfolder’] [‘cs 15jun.pdf’, ‘sc 11jun.pdf’, ‘sc 12dec.pdf’, ‘sc 12jun.pdf’, ‘sc 13jun.pdf’, ‘sc 14jun.pdf’, ‘sc 15jun.pdf’, ‘sc 16dec.pdf’, ‘sc 16jun.pdf’, ‘sc 17jun.pdf’, ‘Syllabus.pdf’, ‘we 10jun.pdf’, ‘we 11jun.pdf’, ‘we 12jun.pdf’, ‘we 13jun.pdf’, ‘we 14jun.pdf’, ‘we 15jun.pdf’, ‘we 16dec.pdf’, ‘we 16jun.pdf’, ‘we 17jun.pdf’, ‘wn 10jun.pdf’, ‘wn 11jun.pdf’, ‘wn 13jun.pdf’, ‘wn 14jun.pdf’, ‘wn 15jun.pdf’, ‘wn 16dec.pdf’, ‘wn 16jun.pdf’, ‘wn 17jun.pdf’, ‘wn jun12.pdf’]

C:\Users\lifei\Desktop\Papers\Newfolder [] [‘readme.txt’]

Actually, these give us Python generator objects. This is why we can traverse on them.

>>> os.walk('C:\\Users\\lifei\\Desktop\\Papers')

<generator object walk at 0x05E0CE10>

11. Conclusion

What we discussed today are just a few methods that Python provides you to work with files and directories. With these, we can create a Python directory, rename, and delete them. You can also traverse them, and check if a path exists. Feel powerful yet? There’s more to come on our journey with Python.
Reasons to Learn Python Programming Language.
For reference
Let us know how did you like our article? Leave a comment if you have any query.

Leave a Reply

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

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.