< previous | Table of Contents | next > |
7.2 FILE HANDLING
File handling enables the programs we write to interact with the files on our computer. This allows us to manipulate files and create new ones.
DIRECTORIES
Files are organized into directories, also known as folders. Directories can contain files and other directories, forming a hierarchy that helps organize data. Python can interact with directories, allowing programs to list files, create new directories, and more.
FILE PATHS
A file path specifies the location of a file on the filesystem. There are two types of file paths.
An absolute path is the complete path from the root of your filesystem to the file. It does not depend on the location of the current program. For example, on Windows C:\Users\Username\Documents\file.txt
or /Users/Username/Documents/file.txt
on macOS or Linux operating systems.
Relative path, as the name indicates, is relative to the current working directory of your program. It is shorter and generally easier to manage within a project as it moves with your project folder. If your program is in /Users/Username/Projects/MyProject
and you want to access file.txt
located in a subfolder called Docs
, the relative path would be Docs/file.txt
. Moving the project to a new location along with its subfolders won’t require changing the relative paths.
For now, as you're just starting out, don't worry too much about the differences. Also, during this course, it's easier for you to use absolute paths, so you don't run into any configuration issues and have a comprehensive overview of what file you're accessing.
OPENING AND CLOSING FILES
Before a file can be read or written, it must be opened using Python's built-in open()
function, which returns a file object. After finishing operations on a file, it's essential to close the file using the close()
method.
FILE MODES
When opening a file, you must specify the mode, which determines the operations you can perform on the file (e.g., read
, write
, append
). File modes include the following.
r
for readingw
for writing. However, remember that this mode overwrites the existing file.a
for appendingr+
,w+
,a+
for reading and writing or appending.
KEY THINGS TO REMEMBER
- Absolute paths specify a file's exact location from the filesystem.
- Relative paths specify the file location relative to the program's current working directory.
- Files can be opened using the
open()
function to access it's contents. It's crucial to close files using theclose()
method to ensure data is saved and system resources freed. - When opening a file, specify the mode in which you want to open the file. If you do not specify a mode, it will open in a read-only capacity.
SELF-CONTROL EXERCISES
< previous | Table of Contents | next > |