Python Directory & File Management – A Quick and Easy Tutorial

Free Python courses with 57 real-time projects - Learn Python

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

How to Get Current Python Directory?

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

>>> os.getcwd()

Output

‘C:\\Users\\lifei\\AppData\\Local\\Programs\\Python\\Python36-32’

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()

Output

b’C:\\Users\\lifei\\AppData\\Local\\Programs\\Python\\Python36-32′

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())

Output

C:\Users\lifei\AppData\Local\Programs\Python\Python36-32

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')

Output

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()

Output

‘C:\\Users\\lifei’

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

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

Output

‘C:\\Users\\lifei’

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()

Output

‘C:\\Users\\lifei’

Finally, you can also use double quotes.

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

Python List Directories and Files

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

>>> os.listdir()

Output

[‘.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()

Output

[‘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.

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()

Output

[‘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.

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()

Output

[‘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’]

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()

Output

[‘Readme.txt’]

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')

Output

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()

Output

[‘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’]

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')

Output

‘C:Users\\lifei\\Desktop’

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

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

Output

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

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')

Output

True

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

Output

False

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

Output

True

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

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

Output

True

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

Output

False

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'):
                print(roots,len(dirs),len(files))

Output

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'):               
                    print(roots,dirs,files)

Output

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')

Output

<generator object walk at 0x05E0CE10>

Python Interview Questions on Directories

  1. How to create a new directory in Python?
  2. How to get a list of directories in Python?
  3. How to compare two directories in Python?
  4. How to check if directory exists in Python?
  5. How to create a parent directory in Python?

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.

Did you know we work 24x7 to provide you best tutorials
Please encourage us - write a review on Google

follow dataflair on YouTube

2 Responses

  1. Dileep says:

    Amazing work by the team. Thanks for such a great content. Keep it up.

    • DataFlair Team says:

      We deeply cherish your kind words and thoughtful consideration. Our team continuously works hard for a better experience, don’t forget to rate us on google.

Leave a Reply

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