Class 4 Lab 6 ‐ OS Module - Justin-Boyd/Python-Class GitHub Wiki

Step 1

  • Create a new Python file in PyCharm by right-clicking the project you created and selecting New > Python File.

Step 2

  • Import the OS and datetime modules.
import os
import datetime

Step 3

  • Create an infinite loop.
while True:

Step 4

  • Within the loop, print the current working directory.
print("Current directory: " + os.getcwd())

Step 5

  • Ask the user for a directory name and store the name in a new variable.
new_dir_name = input("Choose a name for a new directory: ")

Step 6

  • Create the specified directory and navigate to it.
os.mkdir(new_dir_name)
os.chdir(new_dir_name)

Step 7

  • Print the current directory to verify that you moved it to the newly created directory.
print("Current directory: " + os.getcwd())

Step 8

  • Create an if statement that will check if the directory exists.
if new_dir_name:

Step 9

  • Ask the user for a file name and store the name in a new variable.
file_name = input("Choose a text file name ")

Step 10

  • Open the newly created file with read and write permissions
with open("{}.txt".format(file_name), "w+") as new_file

Step 11

  • Print a message to tell the user the file was successfully created and the current date and time.
new_file.write("New file was created, good job!" + str(datetime.datetime.now()))

Step 12

  • Add a line to list the contents of the current working directory and then add a break.
print("The following files are in the directory: " + str(os.listdir()))
break

Step 13

  • Write a try block to handle the file access.
try:

Step 14

  • Add an except block to the try block to handle exceptions.
except:
    print("Error")

Final Code

import os
import datetime

while True:
    print("Current directory: " + os.getcwd())
    new_dir_name = input("Choose a name for a new directory: ")
    os.mkdir(new_dir_name)
    os.chdir(new_dir_name)
    print("Current directory: " + os.getcwd())
    if new_dir_name:
        try:
            file_name = input("Choose a text file name ")
            with open("{}.txt".format(file_name), "w+") as new_file:
                new_file.write("Good job! New file was created on: " + str(datetime.datetime.now()))
                print("The following files are in the directory: " + str(os.listdir()))
                break
        except:
            print("Error")