# Noemi Cabrera
# 15 November 2021
# In this lesson, I learned how to delete files using the os.remove() method, check that a file exists using
# os.path.exists, check if a path is a file or directory using os.path.isdir and os.path.isfile. Also, I learned
# to handle file exceptions using a try/except statement instead of the previous methods I learned and close a file
# despite exceptions using a with statement to open it first. This allows the program to keep running even if an
# exception is raised.
# I had some difficulties trying to figure out why this notebook said some files/directories didn't exist even though the code for the
# examples that I have to run were supposed to be correct. Since this was a problem with the code already provided to me, I do not know
# how to fix it.
# ************** DO NOT MODIFY OR ADD ANYTHING TO THIS CODE SEGMENT ***********
# ************** Click Edit> Clear All Outputs ***********
# ************** This code segment must be run before attempting any of the tasks or examples in this lesson ********************
# ************** This cell is a reset cell to remove (if they exist) the parent_dir and any children or leaves
# It prepares the directories and files necessary to run the examples and complete the tasks.
# This cell can be run first then all others cells in this notebook can be run, then this cell can be rerun
# This is the reset. It uses the import shutil (or shell utility) which you will learn later in the course
import os, shutil # shutil = shell utility has an important method called rmtree()
# linux does not have an equivalent command!
# Navigate to `library` directory (if not already in it)
current_path = os.getcwd()
print(current_path)
if ("content" in current_path):
nb_path = current_path.split("content")[0] # nb_path = the 1st item in the split list
else:
nb_path = current_path
print("Changing working dir to directory above parent_dir")
os.chdir(os.path.join(nb_path,"content"))
current_path = os.getcwd()
print("Current working directory:", current_path)
if (os.path.exists('parent_dir') == True):
shutil.rmtree('parent_dir')
os.mkdir('parent_dir')
os.chdir('parent_dir')
os.mkdir('child1_dir')
os.chdir('../')
current_path = os.getcwd()
print("Current working directory:", current_path)
#JG import os
# Create a file to be deleted
file_path = "parent_dir/tmp_file_to_be_deleted.txt"
f = open(file_path, 'w')
f.close()
# list the content of parent_dir
print('Content of "parent_dir" after creating the file:')
print(os.listdir("parent_dir"))
print()
# delete the file
os.remove(file_path)
# list the content of parent_dir
print('Content of "parent_dir" after removing the file')
print(os.listdir("parent_dir"))
# ************** DO NOT MODIFY OR ADD ANYTHING TO THIS CODE SEGMENT ***********
# ************** This code segment must be run before attempting any of the tasks in this lesson ********************
# It prepares the directories and files necessary to complete the tasks.
import os, random, shutil
# Navigate to `parent_dir` directory (if not already in it)
current_path = os.getcwd()
if ("parent_dir" in current_path):
nb_path = current_path.split("parent_dir")[0]
else:
nb_path = current_path
print("Changing working dir to parent_dir")
os.chdir(os.path.join(nb_path,'parent_dir'))
print("Current working directory:", os.getcwd())
# Remove the `files_exercises` directory (if it exists)
if('files_exercises' in os.listdir()):
print('Removing "files_exercises"')
shutil.rmtree('files_exercises')
# Create a new directory called `files_exercises`
print('Making "files_exercises"')
os.mkdir('files_exercises')
# Change the working directory to `files_exercises`
print('Changing working directory to "files_exercises"')
os.chdir('files_exercises')
# Display the current working directory to verify you are in the correct location
print("Current working directory:", os.getcwd())
# Create 100 text files, the first line of each file is a random number in the range [1000, 9999]
print("Creating 100 text files")
random.seed(25000) # to get the same random numbers every time the setup runs
for i in range(100):
file_name = str(i) + ".txt"
f = open(file_name, 'w')
f.write(str(random.randint(1000, 9999)))
f.close()
f = open('text_file.txt', 'w')
f.write("JG")
f.close()
# Create 5 directories
print("Creating 5 directories")
for i in range(1, 6):
os.mkdir("dir_"+str(i))
print("Environment setup completed!")
# [ ] Complete the following program to delete the first 10 files inside `files_exercises` (0.txt, 1.txt ... 9.txt)
# Make sure the to run the environment setup code before running your own program.
import os
if ('files_exercises' not in os.getcwd()):
print("STOP!!!! Run the environment setup code!")
# list the content of `files_exercises`
print('Content of "files_exercises" before removing the files')
print(os.listdir())
#TODO: delete the first 10 files
os.remove("0.txt")
os.remove("1.txt")
os.remove("2.txt")
os.remove("3.txt")
os.remove("4.txt")
os.remove("5.txt")
os.remove("6.txt")
os.remove("7.txt")
os.remove("8.txt")
os.remove("9.txt")
# list the content of `files_exercises`
print('Content of "files_exercises" after removing the files')
print(os.listdir())
# In this code, the os module is used with the word 'path' so that we can check later if a file exists. A printout states
# the current working directory using os.getcwd() in the print statement. The the path of ficticious file is stored in
# the file_path variable. The if/else statements check if the file exists. If it does, then it checks it's a file. If it's
# a file, then it's removed from the directory. Howver, if it doesn't exist, an statement saying so will display.
import os.path
print("Current working directory:", os.getcwd())
#file_path = "parent_dir/fictitious_file.txt"
file_path = "/content/parent_dir/fictitious_file.txt"
# Removing a file
# Check if the path exists
if (os.path.exists(file_path)):
if (os.path.isfile(file_path)):
os.remove(file_path)
else:
print("Cannot remove a directory")
else:
print("path does not exist")
# In this code, the os module is used with the word 'path' so that we can check later if a file exists. A printout states
# the current working directory using os.getcwd() in the print statement. Then, the path of parent_dir is stored in
# the file_path variable. The if/else statements check if the file exists. If it does, then it checks it's a file. If it's
# a file, then it's removed from the directory. Howver, if it doesn't exist, an statement saying so will display.
import os.path
file_path = "parent_dir"
print("Current working directory:", os.getcwd())
#file_path = "parent_dir/fictitious_file.txt"
file_path = "/content/parent_dir"
# Removing a file
# Check if the path exists
if (os.path.exists(file_path)):
if (os.path.isfile(file_path)):
os.remove(file_path)
else:
print("Cannot remove a directory")
else:
print("path does not exist")
#
# [ ] Write a program to delete all the even numbered files inside `files_exercises`
# Make sure to run the environment setup code before running your own program.
import os
if ('files_exercises' not in os.getcwd()):
print("STOP!!!! Run the environment setup code!")
#TODO: Your code goes here
f_path = "parent_dir"
print("Current working directory:", os.getcwd())
f_path = "parent_dir/files_exercises.txt"
if (os.path.exists(f_path)):
if (os.path.isfile(f_path)):
os.remove(f_path[::2])
else:
print("Cannot remove a directory")
else:
print("path does not exist")
# [ ] Write a program to delete all the directories inside `files_exercises`
# Make sure the to run the environment setup code before running your own program.
import os
if ('files_exercises' not in os.getcwd()):
print("STOP!!!! Run the environment setup code!")
#TODO: Your code goes here
f_path = "parent_dir"
print("Current working directory:", os.getcwd())
f_path = "parent_dir/files_exercises.txt"
if (os.path.exists(f_path)):
if (os.path.isfile(f_path)):
os.remove(f_path)
else:
print("Cannot remove a directory")
else:
print("path does not exist")
# [ ] Write a program to ask the user for a file number,
# then delete the file if it exists or display an appropriate error message if it does not.
# Make sure the to run the environment setup code before running your own program.
# Test your program with the following:
# case 1: user inputs 84, 84.txt should be deleted
# case 2: user inputs 84 (again), a File does not exist message is printed
# case 3: user inputs 5, 5.txt should be deleted
import os
if ('files_exercises' not in os.getcwd()):
print("STOP!!!! Run the environment setup code!")
#TODO: Your code goes here
f_number = input("Enter a file number: ")
f_path = "parent_dir/files_exercises.txt"
if (os.path.exists(f_path)):
if (os.path.isfile(f_number)):
os.remove(f_number)
else:
print("Error - Cannot remove a directory")
else:
print("path does not exist")
# In this code, the os.path module is used. The path to fictitious.txt is stored in the file_path variable.
# Then, a try & except statement is used to check the different exceptions and allow program to keep executing
# despite errors.In this case, the ficticious file is removed from parent_dir because it didn't have any exceptions.
import os.path
file_path = "/content/parent_dir/fictitious_file.txt"
# Remove a file
try:
os.remove(file_path)
except FileNotFoundError as exception_object:
print("Cannot find file: ", exception_object)
except PermissionError as exception_object:
print("Cannot delete a directory: ", exception_object)
except Exception as exception_object:
print("Unexpected exception: ", exception_object)
# In this code, the os.path module is used. The path to parent_dir is stored in the file_path variable.
# Then, a try & except statement is used to check the different exceptions and allow program to keep executing
# despite errors.In this case, parent_dir cannot be removed because it's a directory so the unexpected exception
# print statement will display.
import os.path
file_path = "/content/parent_dir"
# Remove a file
try:
os.remove(file_path)
except FileNotFoundError as exception_object:
print("Cannot find file: ", exception_object)
except PermissionError as exception_object:
print("Cannot delete a directory: ", exception_object)
except Exception as exception_object:
print("Unexpected exception: ", exception_object)
# [ ] Write a program to ask the user for a file number,
# then delete the file if it exists or display an appropriate error message if it does not.
# Use file exception handling instead of file existence tests.
# Make sure to run the environment setup code before running your own program.
# Test your program with the following:
# Case 1: When the user inputs 84, the program should delete the file 84.txt
# Case 2: When the user inputs 84 (again), the program should print a File Not Found error message
# Case 3: When the user inputs 5, the program should delete the file 5.txt
import os
if ('files_exercises' not in os.getcwd()):
print("STOP!!!! Run the environment setup code!")
#TODO: Your code goes here
f_number = input("Enter a file number: ")
f_path = "parent_dir/files_exercises.txt"
try:
os.remove(f_number)
except FileNotFoundError as exception_object:
print("Cannot find file: ", exception_object)
except PermissionError as exception_object:
print("Cannot delete a directory: ", exception_object)
except Exception as exception_object:
print("Unexpected exception: ", exception_object)
# In this code, the path to text_file.txt is stored in the file_path variable. Then a try and except statement
# is used to open this file. Since an exception was raised, the file coudn't be closed using the regular .close() statement.
file_path = "/content/parent_dir/files_exercises/text_file.txt"
try:
file = open(file_path, 'r')
x = int(file.readline()) # Raise an exception if lines are not numeric
file.close() # Might never be reached if file.write raised an error
except Exception as exception_object:
print("Unexpected exception:", exception_object)
print("File is closed?", file.closed)
# In this code, the path to text_file.txt is stored in the file_path variable. Then a try and except statement
# is used to open this file. In this case, the file did close even though an exception was raised because the
# finally clause was used at the end.
file_path = "/content/parent_dir/files_exercises/text_file.txt"
try:
file = open(file_path, 'r')
x = int(file.readline()) #raise an exception if lines are not numeric
except Exception as exception_object:
print("Unexpected exception:", exception_object)
finally:
file.close() # will be executed whether an exception was raised or not
print("File is closed?", file.closed)
# In this code, the path to text_file.txt is stored in the file_path variable. Then a try and except statement
# is used to open this file. In this case, the file did close even though an exception was raised because the
# with statement was used to open the file.
file_path = "/content/parent_dir/files_exercises/text_file.txt"
try:
with open(file_path, 'r') as file:
x = int(file.readline()) #raise an exception if lines are not numeric
except Exception as exception_object:
print("Unexpected exception", exception_object)
print("File is closed?", file.closed)
# [ ] Write a program to print the first line of every file inside `files_exercises`
# Use a `with` statement to open (and close) every file
# Make sure the to run the environment setup code before running your own program.
import os
if ('files_exercises' not in os.getcwd()):
print("STOP!!!! Run the environment setup code!")
#TODO: Your code goes here
file_path = "/content/parent_dir/files_exercises"
with open(files_exercises, 'r') as file:
for line in file:
print(line[0])
print("File is closed?", file.closed)