Class 4 Lab 8 ‐ Copying Files - 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 module.
import os

Step 3

  • Create a new directory.
os.mkdir(r"C:\Users\johnd\Downloads\Cars")

Step 4

  • Create a file in the newly created directory.
with open(r"C:\Users\johnd\Downloads\Cars\Mustang.txt", "a+") as file:
    pass

Step 5

  • Ask the user to provide the file path to copy and assign it to a variable.
path = input("Enter directory path: ")

Step 6

  • Ask the user for a file name and assign it to a variable.
file_name = input("Enter file name: ")

Step 7

  • Ask the user for a name for the file and assign it to a variable
new_name = input("Enter a new name: ")

Step 8

  • Create a txt file to copy and use the system function from the OS module to execute the copy command.
  • Note: Make sure to use the appropriate command for your operating system and that your user has the appropriate permissions for the locations of the files.
os.system(r"copy {}\{} {}\{}".format(path, file_name, path, new_name))

Step 9

  • Place the create directory line in a try block to check if the directory exists before creating it.
try:

Step 10

  • If it exists, print a message informing the user that the directory already exists.
except:
    print("This directory already exists")

Final Code

import os

try:
    os.mkdir(r"C:\Users\johnd\Downloads\Cars")
except:
    print("This directory already exists")
with open(r"C:\Users\johnd\Downloads\Cars\Mustang.txt", "a+") as file:
    pass

path = input("Enter directory path: ")
file_name = input("Enter file name: ")
new_name = input("Enter a new name: ")

os.system(r"copy {}\{} {}\{}".format(path, file_name, path, new_name))