?print-pdf
' Created for
C:\Users\nemsys\tmp.txt
/home/nemsys/tmp.txt
# Windows (the CWD is shown in the prompt )
C:\Users\nemsys\MyDocuments>cd
C:\Users\nemsys\MyDocuments
# Linux/MacOS
nemsys@debian:~/Documents$ pwd
/home/nemsys/Documents
absolute_path = r"C:\Users\Username\Documents\example.txt"
absolute_path = "/home/username/Documents/example.txt"
# if CWD = '/home/username'
relative_path = "Documents/example.txt"
os.getcwd()
and os.chdir()
import os
cwd = os.getcwd()
print("Current Working Directory:", cwd)
import os
# Change the directory to "/path/to/your/directory"
os.chdir("/path/to/your/directory")
# Verify the change
new_dir = os.getcwd()
print("The current working directory has been changed to:", new_dir)
import os
joined_path = os.path.join("folder", "file.txt")
print("Joined Path:", joined_path)
# Output: Joined Path: folder/file.txt
import os
abs_path = os.path.abspath("file.txt")
print("Absolute Path:", abs_path)
# Output: Absolute Path: /full/path/to/file.txt
import os
file_name = os.path.basename("/path/to/file.txt")
print("File Name:", file_name)
# Output: File Name: file.txt
import os
dir_name = os.path.dirname("/path/to/file.txt")
print("Directory Name:", dir_name)
# Output: Directory Name: /path/to
import os
path = "/path/to/file.txt"
exists = os.path.exists(path)
print("Path Exists:", exists)
# Output: Path Exists: True (or False if the path doesn't exist)
import os
file_path = "/path/to/file.txt"
is_file = os.path.isfile(file_path)
print("Is a File:", is_file)
# Output: Is a File: True (or False if the path is not a file)
import os
dir_path = "/path/to/directory"
is_dir = os.path.isdir(dir_path)
print("Is a Directory:", is_dir)
# Output: Is a Directory: True (or False if the path is not a directory)
import os
contents = os.listdir("directory_path")
print(contents)
# Output: ['file1.txt', 'file2.txt', 'folder1', 'folder2']
import os
files = [f for f in os.listdir("directory_path") if os.path.isfile(f)]
print(files)
# Output: ['file1.txt', 'file2.txt']
def list_dir_contents(dir_path):
"""
This function recursively iterates through the directory tree, yielding root, dirs, and files at each level.
It then prints the full path of each directory and file
Args:
dir_path: The path to the directory to list.
Returns:
None
"""
for root, dirs, files in os.walk(dir_path):
for directory in dirs:
full_dir_path = os.path.join(root, directory)
print(f"Directory: {full_dir_path}\n")
for filename in files:
full_file_path = os.path.join(root, filename)
print(f"File: {full_file_path}\n")
dir_path = os.getcwd()
list_dir_contents(dir_path)
import os
os.mkdir("parent_directory")
import os
os.makedirs("parent_directory/child_directory")
import os
os.rmdir("directory_path")
os.rmdir()
removes only empty directory. Otherwise, OSError
is raised.os.removedirs()
, which will delete even non-empty directories.
import shutil
shutil.rmtree("directory_path")
open()
functionfile
object and its methods.
file = open(file_path, mode="r", encoding="None")
file = open(file_path, mode="mode", encoding=encoding)
# Code to read from or write to the file
file.close() # file must be closed!
with
statement, which creates context manager:
with open(file_path, mode="mode", encoding=encoding) as file:
# Code to read from the file
pass
with
statement is executed, Python automatically calls the close() method on the file handle, ensuring that the file is properly closed regardless of whether an exception occurred or not.with
with
statement we do not need finally block, as the context manager will automatically clear the resources.
try:
with open("example.txt", "r") as file:
content = file.read()
except FileNotFoundError:
print("File not found!")
except PermissionError:
print("Permission denied!")
except Exception as e:
print(f"Unexpected error: {e}")
file.read(size)
with open("test_file.txt", "r") as file:
# read entire file content:
contents = file.read()
print(contents)
file.readline(size)
with open("test_file.txt", "r") as file:
# Read first line
first_line = file.readline()
print("First line:", first_line.strip()) # strip() to remove trailing newline
# Read second line
second_line = file.readline()
print("Second line:", second_line.strip()) # strip() to remove trailing newline
file.readlines(size)
with open("test_file.txt", "r") as file:
lines = file.readlines() # get list of all lines
for line in lines:
print(line.strip()) # strip() to remove trailing newline
with open("./test_file.txt", "r") as file:
for line in file:
print(line.strip()) # strip() to remove trailing newline
write()
: Writes a string to the file.
with open("test_file.txt", mode="w", encoding="utf-8") as file:
file.write("Hello, world!\n")
file.write("This is a new line.")
#output:
#Hello, world!
#This is a new line.
writelines()
: Writes a list of strings to the file, without adding any line separators.
data = ['Hello, world!', 'This is a new line.']
lines = [f"{line}\n" for line in data]
with open("test_file.txt", mode="w", encoding="utf-8") as file:
file.writelines(lines)
os.remove(file_path)
import os
# Specify the file path
file_path = "test_file.txt"
# Check if the file exists before attempting to remove it
if os.path.exists(file_path):
# Remove the file
os.remove(file_path)
print(f"{file_path} has been successfully removed.")
else:
print(f"{file_path} does not exist.")
with open()
- ensures automatic file closing.
with open("file.txt", "r") as file:
content = file.read()
try:
with open("file.txt", "r") as file:
content = file.read()
except (FileNotFoundError, PermissionError) as e:
print(f"Error: {e}")
r
, w
, a
, rb
, wb
) - avoids accidental data loss.
with open("file.txt", "a") as file: # Appending instead of overwriting
file.write("New data\n")
with open("large_file.txt", "r") as file:
for line in file:
process(line) # Reads one line at a time
import os
if os.path.exists("file.txt"):
os.remove("file.txt")
These slides are based on
customised version of
framework