Navigating and Manipulating the File System
Python provides built-in functions for opening, reading and writing individual files.The os module adds functions to manipulate files as complete entities.
You start with reading and navigating the file system.You have already seen how you can use os.listdir() to get a directory listings and os.getcwd() to tell you the name of the current working directory.
You can use os.mkdir() to create a new directory and os.chdir() to navigate into a different directory.
You start with reading and navigating the file system.You have already seen how you can use os.listdir() to get a directory listings and os.getcwd() to tell you the name of the current working directory.
You can use os.mkdir() to create a new directory and os.chdir() to navigate into a different directory.
TRY IT OUT
- Change into root directory or create a new directory called ''root".
- Put random or any text files in root directory.
- Start the python interpreter and type the following Python commands.
>>> import os >>> cwd = os.getcwd() >>> print(cwd) /Users/apple/test-project/root >>> os.listdir(cwd) ['fileA.txt', 'fileB.txt', 'ls.txt'] >>> os.mkdir('subdirectory') >>> os.listdir(cwd) ['fileA.txt', 'fileB.txt', 'ls.txt', 'subdirectory'] >>> os.chdir('subdir') Traceback (most recent call last): File "", line 1, in FileNotFoundError: [Errno 2] No such file or directory: 'subdir' >>> os.chdir('subdirectory') >>> os.getcwd() '/Users/apple/test-project/root/subdirectory' >>> os.chdir('..') >>> os.getcwd() '/Users/apple/test-project/root'
HOW IT WORK
After importing os in the first line, you started the current directory in cwd and than . printed it to confirm that you were where you thought were. You than listed its contents . Next, you created a folder called subdirectory and changed into that folder.You verified the move succeeded by calling os.getcwd() again from the new folder and found that the folder had indeed changed. Finally, you changed back up to the previous directory using ".." shortcut and once again verified that it worked with os.getcwd() .
Comments
Post a Comment