January 2019
Beginner
318 pages
8h 23m
English
In this section, we are going to create a script where we will see what functions we can use for working with the directories on your filesystem, which will include creating, listing, and removing the content. Create a script called os_dir_example.py and write the following code in it:
import osdirectory_name = 'abcd'print('Creating', directory_name)os.makedirs(directory_name)file_name = os.path.join(directory_name, 'sample_example.txt')print('Creating', file_name)with open(file_name, 'wt') as f: f.write('sample example file')print('Cleaning up')os.unlink(file_name)os.rmdir(directory_name) # Will delete the directory
Run the script as follows:
$ python3 os_dir_example.pyOutput:Creating abcdCreating abcd/sample_example.txt ...
Read now
Unlock full access