#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"))
/work
Changing working dir to directory above parent_dir
Current working directory: /work
Current working directory: /work
Content of "parent_dir" after creating the file:
['child1_dir', 'tmp_file_to_be_deleted.txt']
Content of "parent_dir" after removing the file
['child1_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!")
Changing working dir to parent_dir
Current working directory: /work/parent_dir
Making "files_exercises"
Changing working directory to "files_exercises"
Current working directory: /work/parent_dir/files_exercises
Creating 100 text files
Creating 5 directories
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())
Content of "files_exercises" before removing the files
['27.txt', '20.txt', 'dir_3', '52.txt', '83.txt', '55.txt', '29.txt', '60.txt', '0.txt', '67.txt', '15.txt', '69.txt', '12.txt', '9.txt', '78.txt', '76.txt', '71.txt', '95.txt', '44.txt', '38.txt', 'text_file.txt', 'dir_4', '92.txt', '43.txt', '31.txt', '36.txt', '13.txt', '8.txt', '14.txt', '68.txt', '1.txt', '66.txt', '61.txt', '6.txt', '54.txt', '85.txt', '28.txt', '53.txt', '82.txt', '21.txt', '26.txt', '37.txt', '30.txt', '93.txt', '42.txt', '94.txt', '45.txt', '39.txt', '70.txt', '77.txt', '79.txt', '33.txt', '99.txt', '48.txt', 'dir_5', '34.txt', '97.txt', '46.txt', '90.txt', '41.txt', '74.txt', '73.txt', '17.txt', '10.txt', '62.txt', '19.txt', '2.txt', '65.txt', '50.txt', '81.txt', '57.txt', '86.txt', '59.txt', '88.txt', '25.txt', 'dir_2', '22.txt', '72.txt', '75.txt', '91.txt', '40.txt', '96.txt', '47.txt', '98.txt', '49.txt', '35.txt', '32.txt', '23.txt', '58.txt', '89.txt', '24.txt', '56.txt', '87.txt', '51.txt', '80.txt', '18.txt', '3.txt', '64.txt', '63.txt', '4.txt', '11.txt', '16.txt', 'dir_1']
Execution Error
FileNotFoundError: [Errno 2] No such file or directory: '5.txt'
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")
Current working directory: /work/parent_dir/files_exercises
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")
Current working directory: /work/parent_dir/files_exercises
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())
['65.txt', '19.txt', '62.txt', '10.txt', '17.txt', '22.txt', '25.txt', '59.txt', '88.txt', '57.txt', '86.txt', '50.txt', '81.txt', '90.txt', '41.txt', '8.txt', '97.txt', '46.txt', '34.txt', '6.txt', '99.txt', '48.txt', '33.txt', '1.txt', 'text_file.txt', '73.txt', '74.txt', '51.txt', '80.txt', '56.txt', '87.txt', '24.txt', '58.txt', '89.txt', '23.txt', 'dir_4', '16.txt', '11.txt', '63.txt', '64.txt', '18.txt', '75.txt', '72.txt', 'dir_3', '32.txt', '0.txt', '35.txt', '7.txt', '98.txt', '49.txt', '9.txt', '96.txt', '47.txt', '91.txt', '40.txt', '71.txt', '76.txt', '78.txt', '36.txt', '4.txt', '31.txt', '3.txt', '92.txt', '43.txt', 'dir_1', '38.txt', '95.txt', '44.txt', '29.txt', '55.txt', '84.txt', '52.txt', '83.txt', '20.txt', '27.txt', '12.txt', '69.txt', '15.txt', '67.txt', '60.txt', '39.txt', '94.txt', '45.txt', '93.txt', '42.txt', '30.txt', '2.txt', '37.txt', '5.txt', '79.txt', '77.txt', 'dir_2', '70.txt', 'dir_5', '61.txt', '66.txt', '68.txt', '14.txt', '13.txt', '26.txt', '21.txt', '53.txt', '82.txt', '28.txt', '54.txt', '85.txt']
['62.txt', '10.txt', '22.txt', '88.txt', '86.txt', '50.txt', '90.txt', '8.txt', '46.txt', '34.txt', '6.txt', '48.txt', 'text_file.txt', '74.txt', '80.txt', '56.txt', '24.txt', '58.txt', 'dir_4', '16.txt', '64.txt', '18.txt', '72.txt', 'dir_3', '32.txt', '0.txt', '98.txt', '96.txt', '40.txt', '76.txt', '78.txt', '36.txt', '4.txt', '92.txt', 'dir_1', '38.txt', '44.txt', '84.txt', '52.txt', '20.txt', '12.txt', '60.txt', '94.txt', '42.txt', '30.txt', '2.txt', 'dir_2', '70.txt', 'dir_5', '66.txt', '68.txt', '14.txt', '26.txt', '82.txt', '28.txt', '54.txt']
# [ ] 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())
sorry this file does not exist
['11.txt', '16.txt', '18.txt', '64.txt', '63.txt', '87.txt', '1.txt', '56.txt', '6.txt', '80.txt', '51.txt', '23.txt', '8.txt', '89.txt', '58.txt', '24.txt', '49.txt', '98.txt', '35.txt', '32.txt', '40.txt', '91.txt', '47.txt', '96.txt', '72.txt', '75.txt', '88.txt', '59.txt', '25.txt', '22.txt', '9.txt', '7.txt', '81.txt', '50.txt', '86.txt', '0.txt', '57.txt', '62.txt', '19.txt', '65.txt', '17.txt', '10.txt', '74.txt', '73.txt', '46.txt', '97.txt', '41.txt', '90.txt', '33.txt', '48.txt', '99.txt', '34.txt', 'text_file.txt', '79.txt', '70.txt', '77.txt', '42.txt', '93.txt', '45.txt', '94.txt', '39.txt', '37.txt', '30.txt', '21.txt', '26.txt', '3.txt', '85.txt', '54.txt', '28.txt', '82.txt', '4.txt', '53.txt', '66.txt', '61.txt', '13.txt', '14.txt', '68.txt', '31.txt', '36.txt', '44.txt', '95.txt', '38.txt', '43.txt', '92.txt', '76.txt', '71.txt', '78.txt', 'dir_5', '15.txt', '69.txt', '12.txt', '60.txt', '67.txt', '83.txt', '52.txt', '2.txt', '55.txt', '29.txt', '27.txt', '20.txt']
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)
Cannot find file: [Errno 2] No such file or directory: '/content/parent_dir/fictitious_file.txt'
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)
Cannot find file: [Errno 2] No such file or directory: '/content/parent_dir'
# [ ] 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())
Cannot find file: [Errno 2] No such file or directory: '5.txt'
['27.txt', '20.txt', 'dir_3', '52.txt', '83.txt', '55.txt', '29.txt', '60.txt', '0.txt', '67.txt', '15.txt', '69.txt', '12.txt', '9.txt', '78.txt', '76.txt', '71.txt', '95.txt', '44.txt', '38.txt', 'text_file.txt', 'dir_4', '92.txt', '43.txt', '31.txt', '36.txt', '13.txt', '8.txt', '14.txt', '68.txt', '1.txt', '66.txt', '61.txt', '6.txt', '54.txt', '85.txt', '28.txt', '53.txt', '82.txt', '21.txt', '26.txt', '37.txt', '30.txt', '93.txt', '42.txt', '94.txt', '45.txt', '39.txt', '70.txt', '77.txt', '79.txt', '33.txt', '99.txt', '48.txt', 'dir_5', '34.txt', '97.txt', '46.txt', '90.txt', '41.txt', '74.txt', '73.txt', '17.txt', '10.txt', '62.txt', '19.txt', '2.txt', '65.txt', '50.txt', '81.txt', '57.txt', '86.txt', '59.txt', '88.txt', '25.txt', 'dir_2', '22.txt', '72.txt', '75.txt', '91.txt', '40.txt', '96.txt', '47.txt', '98.txt', '49.txt', '35.txt', '32.txt', '23.txt', '58.txt', '89.txt', '24.txt', '56.txt', '87.txt', '51.txt', '80.txt', '18.txt', '3.txt', '64.txt', '63.txt', '4.txt', '11.txt', '16.txt', 'dir_1']
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)
Unexpected exception: [Errno 2] No such file or directory: '/content/parent_dir/files_exercises/text_file.txt'
Execution Error
NameError: name 'file' is not defined
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)
Unexpected exception: [Errno 2] No such file or directory: '/content/parent_dir/files_exercises/text_file.txt'
Execution Error
NameError: name 'file' is not defined
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)
Unexpected exception [Errno 2] No such file or directory: '/content/parent_dir/files_exercises/text_file.txt'
Execution Error
NameError: name 'fwile' is not defined
# [ ] 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()
5229
1248
1441
1591
4499
2317
1525
3678
2531
3178
9496
2913
9083
4631
1574
3762
7586
6433
5396
5908
1159
1517
7823
6279
3932
9748
6921
5436
9846
2344
5657
3204
7888
3747
3570
9749
3944
3345
7415
1193
3389
3353
7894
1856
2287
4626
9524
9528
5948
1095
3909
8967
6153
8426
9923
3462
1087
5653
2774
1163
7361
9873
8301
3245
4736
2853
9907
2542
1053
2769
2177
3313
5058
5154
9330
7957
1358
5433
8295
9805
4912
2300
4769
2306
7865
7372
2352
9358
4112
6028
3691
9459
6148
6845
9287
JG
1121
9449
3447
1587
2580