Skip to content

Commit 552bf7f

Browse files
committed
Update 11.2 solutions
1 parent a9ff14e commit 552bf7f

File tree

1 file changed

+10
-11
lines changed

1 file changed

+10
-11
lines changed

ch11-file-input-and-output/2-working-with-paths-in-python.py

Lines changed: 10 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -19,32 +19,31 @@
1919

2020

2121
# Exercise 2
22-
# Display the full paths of any PNG files in the "images" folder
22+
# Display the full paths of any `*.png` files in the "images" folder
2323
file_matches = os.path.join(path, "*.png")
2424
print('All PNG files in "images" folder:')
2525
for file_name in glob.glob(file_matches):
2626
print(file_name)
2727

2828

2929
# Exercise 3
30-
# Change all PNGs to JPGs in the "images" folder and its subfolders
31-
# Could use indexing to get the file extension, but try using
32-
# os.path.splitext()
30+
# Rename all `*.png` files in the "images" folder and its subfolders
31+
# to `*_backup.png`
3332
for current_folder, subfolders, file_names in os.walk(path):
3433
for file_name in file_names:
3534
file_path = os.path.join(current_folder, file_name)
36-
file_tuple = os.path.splitext(
37-
file_path
38-
) # split into (path, extension)
39-
if file_tuple[1].lower() == ".png": # check if extension is PNG
40-
pass # os.rename(file_path, file_tuple[0] + ".jpg")
35+
if file_path.lower().endswith(".gif"):
36+
new_path = file_path[-4] + "_backup.gif"
37+
os.rename(file_path, new_path)
4138

4239

4340
# Exercsie 4
4441
# Check that the two files have been converted to JPGs successfully
45-
print(os.path.exists(os.path.join(path, "png file - not a gif.jpg")))
42+
print(os.path.exists(os.path.join(path, "png file - not a gif_backup.gif")))
4643
print(
47-
os.path.exists(os.path.join(path, "additional files/one last image.jpg"))
44+
os.path.exists(
45+
os.path.join(path, "additional files/one last image_backup.gif")
46+
)
4847
)
4948

5049

0 commit comments

Comments
 (0)