Manage files and folders in Python
In this article, Quantum will work with you on managing files and directories in Python, namely creating folders, renaming folders, listing folders and working with them.
Directory in Python
In the previous article, we became familiar with the file and manipulate files in Python. Here you can simply understand that the directory is where all the files are. Sort the code as well as the file in different folders to easily manage everything.
Python also provides a variety of methods to handle various directory-related operations. The module os has been built to provide methods to help you create, delete, and change folders.
Show current directory
The getcwd () method displays the current working directory, returning the result as a string.
We can also use the getcwdb () method to get the result in bytes.
>>> import os
>>> os.getcwd()
'C:Program FilesPyScripter'
>>> os.getcwdb()
b'C:Program FilesPyScripter'
Change the current directory
The current working directory can be changed by the chdir () method.
chdir () receives a parameter as the name of the directory you want to go from the current directory. It is possible to use either a slash (/) or a backslash () to separate elements in the path, but it is still best to use a backslash ().
>>> os.chdir('C:Python33')
>>> print(os.getcwd())
C:Python33
List of folders and files
You can list all files and subdirectories inside a directory using the listdir () method.
This method takes a path and returns a list of subdirectories and files in that path.
If no path is specified, the returned result will be retrieved from the current working directory.
>>> print(os.getcwd())
C:Python33
>>> os.listdir()
['DLLs',
'Doc',
'include',
'Lib',
'libs',
'LICENSE.txt',
'NEWS.txt',
'python.exe',
'pythonw.exe',
'README.txt',
'Scripts',
'tcl',
'Tools']
>>> os.listdir('G:')
['$RECYCLE.BIN',
'Movies',
'Music',
'Photos',
'Series',
'System Volume Information']
Create a new folder
To create new folders, use the mkdir () method of Module os.
You can choose where to store the new folder by writing the full path to the place you want to create. If the full path is not specified, the new directory will be created in the current working directory.
>>> os.mkdir('test')
>>> os.listdir()
['test']
Rename the folder or file name
You use the rename () method to rename a folder or a file.
>>> os.listdir()
['test']
>>> os.rename('test','new_one')
>>> os.listdir()
['new_one']
Delete the folder or file
To remove a file, you use the remove () method.
Similar to deleting the entire directory, use rmdir ()
>>> os.listdir()
['new_one', 'old.txt']
>>> os.remove('old.txt')
>>> os.listdir()
['new_one']
>>> os.rmdir('new_one')
>>> os.listdir()
[]
Note that the rmdir () method can only delete empty directories.
So to remove a non-empty directory, we can use the rmtree () method inside the shutil module .
>>> os.listdir()
['test']
>>> os.rmdir('test')
Traceback (most recent call last):
.
OSError: [WinError 145] The directory is not empty: 'test'
>>> import shutil
>>> shutil.rmtree('test')
>>> os.listdir()
[]
So you are familiar with the most basic operations with the directory. The os module in Python still provides a lot of other useful methods to perform operations with files and folders. Stay tuned for the next lessons of Quantrimang.
Wish you learn Python very fun!
See more:
- Matrix in Python
- Module in Python
- The Python exercise has a solution
Previous article: Working with File in Python
Next lesson: Error and Exception in Python
You should read it
- Multiple choice quiz about Python - Part 3
- Bookmark 5 best Python programming learning websites
- For in Python loop
- 5 choose the best Python IDE for you
- What is Python? Why choose Python?
- Module time in Python
- Python data type: string, number, list, tuple, set and dictionary
- How to install Python on Windows, macOS, Linux
May be interested
- More than 100 Python exercises have solutions (sample code)more than 100 python code examples are shared by guy zhiwehu on github, however, the solution of this series is written on the old python version. following tipsmake.com will be vietnameseized and edited to suit python 3.x to help you learn and practice python.
- Secure folders with Secure Folders softwareprotect folders, applications on your computer to help you manage your computer better and prevent others from viewing important folders. secure folders is free software with a simple interface, easy to use and compatible with all versions of windows.
- Manage Gmail with foldersgmail does not allow users to create 'folders' to manage and categorize emails according to different criteria such as yahoo mail, windows live mail.
- How to compress and decompress files and folders on a Macon the mac, there is a built-in tool to compress and decompress files and folders that users do not need to install the application, if only the basic compression and decompression features.
- How to create a library book borrowing system in Pythonthe book borrowing system helps librarians conveniently manage books and borrow books in the library. here is a tutorial on how to create a library book borrowing system in python .
- Bookmark 5 best Python programming learning websitesif you are a developer or you are studying and want to stick with this industry, learn python to add a highlight in your journey.
- For in Python loopin this article, we will learn more about for for loop in python as well as its variations, how to use for to repeat a string of elements in python such as list, string or other iterative objects.
- Instructions on how to encrypt files and folders on Ubuntuubuntu possesses many advanced security features that users may not know about. for example, libreoffice users can encrypt files and folders on ubuntu extremely simply but extremely securely. so what is that feature and how to use it on ubuntu for files and folders?
- How to manage files by tag on Windows 10to manage and access folders quickly, as well as files on windows 10, users can install filetag applications.
- How to share files and folders in Dropboxhow to share files and folders in dropbox. to share files or folders of dropbox, you need to open your file folder, click on files in the left column under the dropbox icon.