External Exam Download Resources Web Applications Games Recycle Bin

Files READ/WRITE

files create open read.py

#----------- file mode paramters:
#'r' open for reading (default)
#'w' open for writing, truncating the file first
#'x' open for exclusive creation, failing if the file already exists
#'a' open for writing, appending to the end of the file if it exists

file = open("words.txt", "w")
file.write("Some text\n")
file.write("Some more text\n")
file.close()

#\n = new line

#--------------------------------
#using 'with' guarantees
#the file is closed after use:

with open("words.txt", "r") as file:    
    for line in file:
        print(line.strip("\n"))

#.strip("\n") = strips new line
#.rstrip() = right strip

move file.py

file = open("move.me", "w")
file.write("Off i go\n")
file.write("To another folder location\n")
file.close()

import os
if not(os.path.isdir("new_destination_folder/")):
    os.makedirs("new_destination_folder/")
os.rename("move.me", "new_destination_folder/move.me")

#-----HELPFUL BOOLEAN EXPRESSIONS:
#os.path.isdir("directory")
#os.path.exists("directoryorfile")

copy using shutil.py

file = open("copy.me", "w")
file.write("Duplicate me\n")
file.write("For a backup somewhere\n")
file.close()

import shutil
shutil.copyfile('copy.me', 'backup.txt')

delete.py

file = open("gone.txt", "w")
file.write("time to say goodbye\n")
file.write("delete my file\n")
file.close()

#put an input() here
#if you wish to pause execution

import os
if os.path.exists("gone.txt"):
  os.remove("gone.txt")
else:
  print("The file does not exist")

remove folder.py

import os
if not(os.path.isdir("temp_folder/")):
    os.makedirs("temp_folder/")

#put an input() here if you need to pause
#to see this working

os.rmdir("temp_folder/")
  1. Write a program that adds 1 plus 1 together and outputs the answer

  2. Input a number from the user, then return the number inputted from the user multiplyed by 10.

  3. Input a number from the user, then return the number inputted from the user multiplyed by itself. For example, if the user inputs 5, your program would return 25.

  4. Create a program that inputs my postcode as a string. Create a variable NEIGHBOUR and use it to store (using the int function) the inputted postcode minus one. Output "The postcode in the next suburb is NEIGHBOUR" (where NEIGHBOUR is the value of the neighbouring postcode.)

  5. Extension:


  6. Write a program that calculates the area of a circle from a given radius input

  7. Ask a user to input their age. Print out their year of birth by using the formula year of birth = current year - age (in years)

  8. Write a program that inputs two whole numbers into two variables (call the variables num1 and num2), then outputs the sum, product and difference of those two numbers.

  9. Write a program that inputs a whole number, and prints an arrow like this: ---> but with the length of the arrow (or number of dashes in the arrow) equal to the whole number inputted