Path: blob/master/12-Advanced Python Modules/01-Opening-and-Reading-Files-Folders.ipynb
666 views
Opening and Reading Files
So far we've discussed how to open files manually, one by one. Let's explore how we can open files programatically.
Review: Understanding File Paths
Create Practice File
We will begin by creating a practice text file that we will be using for demonstration.
Getting Directories
Python has a built-in os module that allows us to use operating system dependent functionality.
You can get the current directory:
Listing Files in a Directory
You can also use the os module to list directories.
Moving Files
You can use the built-in shutil module to to move files to different locations. Keep in mind, there are permission restrictions, for example if you are logged in a User A, you won't be able to make changes to the top level Users folder without the proper permissions, more info
Deleting Files
NOTE: The os module provides 3 methods for deleting files:
os.unlink(path) which deletes a file at the path your provide
os.rmdir(path) which deletes a folder (folder must be empty) at the path your provide
shutil.rmtree(path) this is the most dangerous, as it will remove all files and folders contained in the path. All of these methods can not be reversed! Which means if you make a mistake you won't be able to recover the file. Instead we will use the send2trash module. A safer alternative that sends deleted files to the trash bin instead of permanent removal.
Install the send2trash module with:
at your command line.
Walking through a directory
Often you will just need to "walk" through a directory, that is visit every file or folder and check to see if a file is in the directory, and then perhaps do something with that file. Usually recursively walking through every file and folder in a directory would be quite tricky to program, but luckily the os module has a direct method call for this called os.walk(). Let's explore how it works.
Excellent, you should now be aware of how to work with a computer's files and folders in whichever directory they are in. Remember that the os module works for any oeprating system that supports Python, which means these commands will work across Linux,MacOs, or Windows without need for adjustment.