Module 3
Ch 9
READING AND WRITING FILES
Why Save Files?
• - Variables store data temporarily
• - To keep data permanently, save to a file
• - A file can store large data, even gigabytes
What is a File?
• - A digital document that stores data
• - File contents are usually a long string
• - Files can be read, created, and written using
Python
What is a File Path?
• - A file path shows where a file is located
• - Example: C:\Users\Al\Documents\
[Link]
• - It includes folders and the filename
Folder Hierarchy Example
• C:\
└── Users\
└── Al\
└── Documents\
└── [Link]
C:\ is the root folder. Everything else is stored inside it.
Users, Al, and Documents are folders (or directories).
[Link] is a file stored inside the Documents
folder.
File Extensions
• The part after the dot in a filename (e.g., .docx)
• Tells you the file type
• .docx = Word Document, .txt = Text File
Operating System Differences
Summary
• - Files store data permanently
• - File paths locate files in folders
• - Extensions define file types
• - OS differences affect path style and
sensitivity
Backslash on Windows and Forward Slash
on macOS and Linux
• - Windows uses backslashes: \
• - macOS and Linux use forward slashes: /
• - Writing code for all OS requires handling
both types.
Use pathlib for Compatibility
• - Use Path() from the pathlib module.
• - Automatically handles correct separators
based on OS.
• - Example: Path('spam', 'bacon', 'eggs')
•
Example in Python
>>> from pathlib import Path
Shell
• >>> Path('spam', 'bacon', 'eggs’)
• On windows
WindowsPath('spam/bacon/eggs')
• >>> str(Path('spam', 'bacon', 'eggs'))
• 'spam\\bacon\\eggs'
• The double backslashes are just how Python
shows a single \ in strings.
Why Forward Slashes Show Up
• - Even on Windows, Path() shows forward
slashes
• - Open source tools and Linux preference
• - str() gives the true path string (with
backslashes on Windows)
• Even on Windows, you may see forward slashes
(/) in outputs because many tools are made to
work like Linux. But don't worry—the file will
still work on your system!
To Get the Actual Path String
• You can convert a Path
• str(Path('spam', 'bacon', 'eggs'))
• # On Windows: 'spam\\bacon\\eggs'
• object into a text path using str():
Path Object Types
• On Windows: returns WindowsPath object
• - On Linux/macOS: returns PosixPath object
• - These behave the same, but with different
formatting
Joining Paths with a Loop
• >>> from pathlib import Path
• >>> myFiles = ['[Link]', '[Link]',
'[Link]']
• >>> for filename in myFiles:
• print(Path(r'C:\Users\Al', filename))
• C:\Users\Al\[Link]
• C:\Users\Al\[Link]
• C:\Users\Al\[Link]
Special Note on Backslashes
• - Backslashes can't be used in filenames on
Windows
• - But can be part of filenames on Linux/macOS
• - So avoid hardcoding backslashes—use
pathlib!
pathlib vs [Link]
• - pathlib introduced in Python 3.4
• - Preferred over old [Link] methods
• - For Python 2.7, use pathlib2 (install via pip)
Summary
• - Different OS use different path formats
• - Use pathlib. Path to handle paths
automatically
• - Ensures your Python code works everywhere
Using the / Operator to Join Paths
• understand how to safely join file paths using
the / operator with pathlib, and why it is
prefered over older methods.
What Is Path Joining?
• When writing code that works with files and
folders, you often need to combine folder
names and filenames into a single full path.
For example:
• "C:/Users/Al" + "/spam"
This approach works, but it's:
• Error-prone (especially with slashes on different OSes),
• Harder to read and maintain.
The Better Way: [Link] and the / Operator
• The pathlib module provides a much cleaner and more
reliable way to join paths using the / operator.
• Here’s how it works:
from pathlib import Path
path = Path('spam') / 'bacon' / 'eggs' / 'ham'
print(path)
That’s print
WindowsPath('spam/bacon/eggs/ham')
How the / Operator Works
• When you use / with Path objects:It
automatically joins paths using the correct
format for the operating system.
• The first item must be a Path object.
-Path('spam') / 'bacon' / 'eggs’
This works — it results in
spam/bacon/eggs.
This will give error
-'spam' / 'bacon'
Because strings don't know how to use / this way.
This builds a full path by chaining with /.
Why Not Use [Link]() or +?
Old method (not safe):
Problems: Needs double backslashes.
Only works correctly on Windows.
Bug-prone and hard to maintain.
Better method with pathlib:
Results
WindowsPath('C:/Users/Al/spam')
Getting & Changing Current Working Directory
(CWD)
• [Link]() ➜Gets the current working directory.
• [Link]('new_path') ➜ Changes it.
Note: pathlib doesn’t have a function to change the
current directory — only [Link]() does.
The Home Directory
• All users have a folder for their own files on the computer
called the home directory or home folder.
• You can get a Path object of the home folder by calling
[Link]():
>>> [Link]()
WindowsPath('C:/Users/Al')
• The home directories are located in a set place depending
on your operating system:
• On Windows, home directories are under C:\Users.
• On Mac, home directories are under /Users.
• On Linux, home directories are often under /home.
• Your scripts will almost certainly have permissions to read
and write the files under your home directory, so it’s an ideal
place to put the files that your Python programs will work
Absolute vs. Relative Paths
There are two ways to specify a file path:
An absolute path, which always begins with the root
folder
A relative path, which is relative to the program’s
current working directory
• There are also the dot (.) and dot-dot (..) folders.
These are not real folders but special names that can
be used in a path. A single period (“dot”) for a folder
name is shorthand for “this directory.” Two periods
(“dot-dot”) means “the parent folder.”
The .\ at the start of a relative path is optional. For example, .\[Link] and
[Link] refer to the same file.
Creating New Folders Using the [Link]()
Function
• Your programs can create new folders (directories) with
the [Link]() function. Enter the following into the
interactive shell:
• >>> import os
• >>> [Link]('C:\\delicious\\walnut\\waffles’)
• This will create not just the C:\delicious folder but also a
walnut folder inside C:\delicious and a waffles folder inside
C:\delicious\walnut. That is, [Link]() will create any
necessary intermediate folders in order to ensure that the
full path exists. Figure 9-3 shows this hierarchy of folders.
• To make a directory from a Path
object, call the mkdir() method.
For example, this code will create
a spam folder under the home
folder on my computer:
>>> from pathlib import Path
>>>Path(r'C:\Users\Al\spam').mkdir()
• Note that mkdir() can only make
one directory at a time; it won’t
make several subdirectories at
once like [Link]().
Handling Absolute and Relative Paths
• The pathlib module provides methods for
checking whether a given path is an absolute
path and returning the absolute path of a
relative path.
• Calling the is_absolute() method on a Path
object will return True if it represents an
absolute path or False if it represents a
relative path.
• Using the pathlib Module
1. Getting the Current Working Directory
from pathlib import Path
[Link]()
Output:
WindowsPath('C:/Users/Al/AppData/Local/
Programs/Python/Python37')
This is the full (absolute) path where your Python
program is currently running.
2. Checking If a Path Is Absolute Use is_absolute()
method.
[Link]().is_absolute() # because
o/p True cwd is
always absolute
Path('spam/bacon/eggs').is_absolute()
o/p False # because it's a relative
path
3. Converting Relative Path to Absolute
To get an absolute path from a relative path, you
can put [Link]() / in front of the relative Path
object.
>>>Path('my/relative/path’)
To make it absolute, add it to the current
working directory:
>>>[Link]() / Path('my/relative/path’)
output
WindowsPath('C:/Users/Al/AppData/.../my/
relative/path')
You can also use [Link]() if the path is
relative to your home dir.
>>> [Link]() / Path('my/relative/path')
Using the [Link] Module
Let’s now look at how to do similar things using the [Link] module.
import os
1. Get Absolute Path
>>> [Link]('.')
Output:
'C:\\Users\\Al\\AppData\\Local\\Programs\\Python\\Python37’
2. . refers to the current directory.
2. abspath() converts it to the full absolute path.
>>> [Link]('.\\Scripts’)
'C:\\Users\\Al\\AppData\\Local\\Programs\\Python\\Python37\\
Scripts'
2. Check If a Path Is Absolute
>>>[Link]('.')
# Output: False (because '.' is a relative reference)
>>>[Link]([Link]('.'))
# Output: True (because we converted it to absolute)
3. Find Relative Path Between Two Locations
>>>[Link]('C:\\Windows', 'C:\\')
# Output: 'Windows’
>>>[Link]('C:\\Windows', 'C:\\spam\\eggs')
# Output: '..\\..\\Windows'
'..' means "go up one level" (to the parent folder).
So '..\\..\\Windows' means:
• Go up two levels from 'C:\\spam\\eggs', then enter the 'Windows' folder.
• When the relative path is within the same parent folder as the path, but is
within subfolders of a different path, such as 'C:\\Windows' and 'C:\\spam\\
eggs', you can use the “dot-dot” notation to return to the parent folder.
Getting the Parts of a File Path
• This will explain how you can extract different
parts of a file path using a Path object in
Python’s pathlib module. These attributes help
you dissect a file path into its components —
like the drive, folder, filename, extension, etc.
The parts of a file path include the following:
● The anchor, which is the root folder of the filesystem
● On Windows, the drive, which is the single letter that
often denotes a physical hard drive or other storage
device
● The parent, which is the folder that contains the file
● The name of the file, made up of the stem (or base
name) and the suffix (or extension)
• To extract each attribute from the file path, enter the
following into the interactive shell:
>>> p = Path('C:/Users/Al/[Link]’)
>>> [Link]
'C:\\’
>>> [Link] # This is a Path object, not a string.
WindowsPath('C:/Users/Al’)
>>> [Link]
'[Link]’
>>> [Link]
'spam’
>>> [Link]
'.txt’
>>> [Link]
'C:'
[Link]().parent
This gives you the immediate parent folder.
>>> [Link]()
WindowsPath('C:/Users/Al/AppData/Local/Programs/Python/Pyt
hon37’)
>>> [Link]().parents[0]
WindowsPath('C:/Users/Al/AppData/Local/Programs/Python’)
>>> [Link]().parents[1]
WindowsPath('C:/Users/Al/AppData/Local/Programs’)
>>> [Link]().parents[2]
WindowsPath('C:/Users/Al/AppData/Local’)
>>> [Link]().parents[3] WindowsPath('C:/Users/Al/AppData’)
>>> [Link]().parents[4] WindowsPath('C:/Users/Al’)
>>> [Link]().parents[5] WindowsPath('C:/Users’)
>>> [Link]().parents[6] WindowsPath('C:/')
Finding File Sizes and Folder Contents
• os: Provides a way of interacting with the
operating system.
• [Link]: A submodule of os that helps with file
path operations.
Basic Functions
1. [Link](path)
Returns the size in bytes of the file at the given
path.
Ex:
import os
print([Link]('C:\\Windows\\System32\\
[Link]'))
# Output: 776192
2. [Link](path)
Returns a list of names (files and folders) in the given
directory.
import os
print([Link]('C:\\Windows\\System32'))
# Output: ['0409', '[Link]', '[Link]', 'drivers', ...]
Note: This lists both files and folders in the directory.
Find Total Size of All Files in a Directory
• To find the total size of only files in a directory
(ignoring subfolders), you can combine both
functions:
SUMMARY
2.3 Checking Path Validity
Key Functions from [Link]:
Function What it checks Returns
Does the path (file or
[Link](path) True / False
folder) exist?
Does the path exist and is it
[Link](path) True / False
a file?
Does the path exist and is it
[Link](path) True / False
a folder?
• Examples:
>>>[Link]('C:\\Windows')
✔️True → The folder C:\Windows does exist on the computer.
>>>[Link]('C:\\some_made_up_folder')
❌ False → There is no folder or file at C:\
some_made_up_folder.
>>>[Link]('C:\\Windows\\System32')
✔️True → The path exists and it's a folder.
>>>[Link]('C:\\Windows\\System32')
❌ False → This path exists, but it's a folder, not a file.
>>>[Link]('C:\\Windows\\System32\\[Link]')
❌ False →
>>>[Link]('C:\\Windows\\System32\\[Link]')
✔️True
3. The File Reading/Writing Process
🔹 1. Understanding File Types
✅ Plaintext Files
•These contain only basic characters (letters,
numbers,
symbols).
•They do not include formatting (no font size, bold,
etc.).
Examples:
.txt (Notepad files)
.py (Python source code)
✅ Binary Files
These contain data not meant to be read as plain text.
Examples:
.docx (Word), .pdf, .jpg, .exe
If you open them in Notepad, you’ll see gibberish
because they contain encoded data.
🔸 In most beginner Python programs, we work only
with plaintext files, not binary ones.
There are three steps to reading or writing files in Python.
1. Call the open() function to return a File object.
2. Call the read() or write() method on the File object.
3. Close the file by calling the close() method on the File
object.
✅ Step 1: Open the File
python
Syntax: file_object = open('[Link]', 'mode')
'[Link]': Name or path of the file.
'mode': What you want to do with the file:
'r' → Read
'w' → Write (overwrite if file exists)
'a' → Append (add to end of file)
'r+' → Read and write
Example:
python
>>>file = open('[Link]', 'r') # Open file for reading
✅ Step 2: Read from or Write to the File python
content = [Link]() # Reads entire content
line = [Link]() # Reads one line
lines = [Link]() # Reads all lines as a list
[Link]("Hello") # Writes to the file (if opened in write or append mode)
✅ Step 3: Close the File
>>>[Link]()
EX: Reading file EX: Writing File
Use with statement (Best Practice)
This automatically closes the file:
3.1 Opening Files with the open() Function
• To open a file with the open() function, you pass it a string
path indicating the file you want to open; it can be either an
absolute or relative path.
• The open() function returns a File object.
• Try it by creating a text file named [Link] using Notepad or
TextEdit. Type Hello world! as the content of this text file and
save it in your user home folder.
>>> helloFile = open('C:\\Users\\your_home_folder\\[Link]')
• If you’re using OS X, enter the following into the interactive
shell instead:
>>> helloFile = open('/Users/your_home_folder/[Link]')
• When a file is opened in read mode, Python
lets you only read data from the file; you can’t
write or modify it in any way.
• Read mode is the default mode for files you
open in Python.
• if you don’t want to rely on Python’s defaults,
you can explicitly specify the mode by passing
the string value 'r' as a second argument to
open().
• open('/Users/asweigart/ [Link]', 'r') and
open('/Users/asweigart/[Link]')
• 3.2 Reading the Contents of Files
• If you want to read the entire contents of a file as
a string value, use the File object’s read() method
• >>> helloContent = [Link]()
• >>> helloContent
'Hello world!'
• Alternatively, you can use the readlines() method to get a list
of string values from the file, one string for each line of text.
• For example, create a file named [Link] in the same
directory as [Link] and write the following text in it:
• Make sure to separate the four lines with line breaks
>>> sonnetFile = open('[Link]')
>>> [Link]()
3.3 Writing to Files
➢ Python allows you to write content to a file in a way similar to
how the print() function “writes” strings to the screen.
➢ You can’t write to a file you’ve opened in read mode, though.
Instead, you need to open it in “write plaintext” mode or “append
plaintext” mode, or write mode and append mode for short.
➢Write mode will overwrite the existing file and start from scratch,
just like when you overwrite a variable’s value with a new value
• Pass 'w' as the second argument to open() to open the file in write
mode Append mode, on the other hand, will append text to the
end of the existing file.
• Pass 'a' as the second argument to open() to open the file in
append mode.
• If the filename passed to open() does not exist, both write and
append mode will create a new, blank file.
4. Saving Variables with the shelve Module
• You can save variables in your Python programs to binary
shelf files using the shelve module.
• This way, your program can restore data to variables from the
hard drive.
• The shelve module will let you add Save and Open features to
your program.
• For example, if you ran a program and entered some
configuration settings, you could save those settings to a shelf
file and then have the program load them the next time it is
run
Saving Data
• Example: Loading the Data Later
• Using keys() and values()
5. Saving Variables with the [Link]()
Function
• [Link]() function will “pretty print” the contents
of a list or dictionary to the screen,
• while the [Link]() function will return this
same text as a string instead of printing it file will be
your very own module that you can import whenever
you want to use the variable stored in it.
>>> import pprint
>>> cats = [{'name': 'Zophie', 'desc': 'chubby'}, {'name': 'Pooka', 'desc':
'fluffy’}]
• Converting data into string using pformat
>>> [Link](cats)
"[{'desc': 'chubby', 'name': 'Zophie'}, {'desc': 'fluffy', 'name': 'Pooka'}]"
• Write it to a .py file
OutPut
cats = [{'desc': 'chubby', 'name': 'Zophie'}, {'desc': 'fluffy', 'name':
'Pooka’}]
• Import and Use the Data