# My name is Pavan Kumpatla and today's date is November 23, 2021
# I learned how to use the "with" along with files and more
# I don't think I understood the tasks (I had help so I'm planning to review soon)
# ************** 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
# imports
if ('files_exercises' not in os.getcwd()):
# if files_exercise is not in the cwd
print("STOP!!!! Run the environment setup code!")
# prints
# list the content of `files_exercises`
print('Content of "files_exercises" before removing the files')
# prints
print(os.listdir())
# prints, lists directory
#TODO: delete the first 10 files
# list the content of `files_exercises`
print('Content of "files_exercises" after removing the files')
# prints
print(os.listdir())
# prints, lists directory
# NOTE:- I'm not sure I understood this
import os.path
# imports
print("Current working directory:", os.getcwd())
# prints, prints cwd
#file_path = "parent_dir/fictitious_file.txt"
file_path = "/content/parent_dir/fictitious_file.txt"
# stores
# Removing a file
# Check if the path exists
if (os.path.exists(file_path)):
# if file_path exists
if (os.path.isfile(file_path)):
# if it is a file
os.remove(file_path)
# remove it
else:
# else
print("Cannot remove a directory")
# prints
else:
# else
print("path does not exist")
# prints
import os.path
# imports
file_path = "parent_dir"
# stores
print("Current working directory:", os.getcwd())
# prints, prints cwd
#file_path = "parent_dir/fictitious_file.txt"
file_path = "/content/parent_dir"
# stores
# Removing a file
# Check if the path exists
if (os.path.exists(file_path)):
# if file_path exists
if (os.path.isfile(file_path)):
# if it is a file
os.remove(file_path)
# remove it
else:
# else
print("Cannot remove a directory")
# prints
else:
# else
print("path does not exist")
# prints
# [ ] Write a program to delete all the even numbered files inside `files_exercises`
# Make sure the to run the environment setup code before running your own program.
import os
# imports
if ('files_exercises' not in os.getcwd()):
# if files_exericse is not in cwd
print("STOP!!!! Run the environment setup code!")
# prints
#TODO: Your code goes here
print("Current working directory:", os.getcwd())
# prints, prints cwd
file_path = "parent_dir/files_exercises.txt"
# stores
if os.path.exists(file_path):
# if file_path exists
if os.path.isfile(file_path):
# if file_path is a file
os.remove(file_path[::2])
# remove all even numbered files (interval of 2)
else:
# else
print("The directory cannot be removed")
# prints
else:
# else
print("Path does not exist")
# prints
# [ ] 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
# imports os
if ('files_exercises' not in os.getcwd()):
# if files_exercise is not in cwd
print("STOP!!!! Run the environment setup code!")
# prints
#TODO: Your code goes here
file_path = "parent_dir"
# stores
if os.path.exists(file_path):
# if file_path exists
if os.path.isfile(file_path):
# if file_path is a file
os.remove(file_path)
# remove it
else:
# else
print("The directory cannot be removed")
# prints
else:
# else
print("The path does not exist")
# prints
# [ ] 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
file_number = input("Enter A File Number: ")
# gathers user input
file_path = "parent_dir/files_exercises.txt"
# stores
if (os.path.exists(file_path)):
# if file_path exists
if (os.path.isfile(file_number)):
# if file_number is a file
os.remove(file_number)
# remove it
else:
# else
print("ERROR! You Cannot Remove A Directory!")
# prints
else:
# else
print("The path does not exist")
# prints
import os.path
# imports
file_path = "/content/parent_dir/fictitious_file.txt"
# stores
# 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)
# tries, if there is a error, puts in a message with print instead of a error message
import os.path
# imports
file_path = "/content/parent_dir"
# stores
# 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)
# tries, if there is a error, puts in a message with print instead of a error message
# [ ] 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
file_numer = input("Type in File Number:- ")
# gathers user input
file_path = "parent_dir/files_exercises.txt"
# stores
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)
# tries, if there is a error, puts in a message with print instead of a error message
file_path = "/content/parent_dir/files_exercises/text_file.txt"
# stores
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)
# tries, if there is a error, puts in a message with print instead of a error message
print("File is closed?", file.closed)
# prints
file_path = "/content/parent_dir/files_exercises/text_file.txt"
# stores
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
# tries, if there is a error, puts in a message with print instead of a error message
print("File is closed?", file.closed)
# prints
file_path = "/content/parent_dir/files_exercises/text_file.txt"
# stores
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)
# tries, if there is a error, puts in a message with print instead of a error message
print("File is closed?", file.closed)
# prints
# [ ] 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"
# stores
with open(files_exercises, 'r') as file:
# opens file_exercises in read mode as "file"
for line in file:
# for every line in file
print(line[0])
# prints
print("File is closed?", file.closed)
# prints