#Conner Kahn
#11/15
#I learned more about file control
# ************** 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))
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
for x in range(10):
os.remove(str(x) + '.txt')
# list the content of `files_exercises`
print('Content of "files_exercises" after removing the files')
print(os.listdir())
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")
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 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!")
print(os.listdir())
#TODO: Your code goes here
for x in range(100):
if x % 2 == 1:
if os.path.exists(str(x) + '.txt'):
os.remove(str(x) + ".txt")
print(os.listdir())
# [ ] 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
for x in range(1,5):
os.rmdir("dir_"+ str(x))
# [ ] 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
x = input("input a numer")
if os.path.exists(str(x) + '.txt'):
os.remove(str(x) + '.txt')
print('file #', x, "has been deleted")
else:
print("sorry this file does not exist")
print(os.listdir())
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)
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
x = input("input a number of a file")
try:
os.remove(str(x)+'.txt')
print("file #", x, 'has been deleted')
except FileNotFoundError as exception_object:
print("Cannot find file: ", exception_object)
print(os.listdir())
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)
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)
file_path = "/content/parent_dir/files_exercises/text_file.txt"
try:
with open(file_path, 'r') as fwile:
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?", fwile.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.
file_path = "/content/parent_dir/files_exercises"
import os, os.path
if ('files_exercises' not in os.getcwd()):
print("STOP!!!! Run the environment setup code!")
#TODO: Your code goes here
for x in os.listdir('/work/parent_dir/files_exercises'):
if os.path.isfile(x):
z = open(x, 'r')
print(z.readline())
z.close()