Files Exercises

  1. File Basics
    1. Filenames:
      1. Discuss with your neighbor the difference between the following (and provide examples of each):
        • Relative paths and absolute paths
        • Unix/Linux/macOS and Windows filenames
      2. Which type of path is better for each of the following scenarios?
        • Accessing a system file
        • Making your code more portable, for example, to be shared with other people
    2. List the 3 most common file modes and explain any potentially negative side effects:
    3. Discover one of the other file modes. Explain to someone else what it is and when you would use it.
  2. Opening Files
    1. Identify the two parts for opening a file:
    2. Write code to open a file named testCases.txt.
    3. Write code to open a file named output.csv.
    4. Write code that prompts the user for a filename and then opens that file. If the file does not exist, tell the user that it does not exist and prompt them again for a filename and try to open that file. Repeat this process until the file is successfully opened.
  3. Closing Files
    1. Give the following code:
      inputFileObj = open( filename, mode )
      write code to close the file.
  4. Reading From Files
    1. Discuss with your neighbor the difference between the following (discuss what each returns, any arguments, when you'd use each one of them):
      • fileObject.read()
      • fileObject.readline()
      • fileObject.readlines()
  5. Loops and Files
    1. Reorder (and indent as necessary) the following lines to make a Python script that displays the sum of all of the lines in values.txt:
      1. print( 'ERROR! Unable to open or read from', filename)
      2. print( 'Total of the values in', filename, 'is', total)
      3. import sys
      4. except:
      5. for line in inputFileObj:
      6. if line.isdigit() == True:
      7. try:
      8. filename = "values.txt"
      9. inputFileObj = open( filename, mode )
      10. inputFileObj.close()
      11. mode = 'r' # read mode
      12. sys.exit()
      13. total += int( line )
      14. total = 0
    2. The file letters.txt has the letters A-Z, each one on its own line. What will the following code output and why?
      # A real example, but an INCORRECT solution
      
      import sys
      
      filename = "letters.txt"
      mode = 'r'  # read mode
      
      try:
          inputFileObj = open( filename, mode)
      
          for line in inputFileObj:
              line = inputFileObj.readline()
              print(line, end='')
      
      except:
          print("ERROR! Unable to open or read from", filename)
          sys.exit()
      finally:
          inputFileObj.close()
      
    3. The file letters.txt has the letters A-Z, each one on its own line. What will the following code output and why?
      # A real example, but an INCORRECT solution
      
      import sys
      
      filename = "letters.txt"
      mode = 'r'  # read mode
      
      try:
          inputFileObj = open( filename, mode)
      
          line = inputFileObj.readline()
          while line != '':
              line = inputFileObj.readline()
              print(line)
      
      except:
          print("ERROR! Unable to open or read from", filename)
          sys.exit()
      finally:
          inputFileObj.close()
      
  6. Writing To Files
    1. What will be displayed after executing the following code:
      import sys  # exit()
      
      filename = 'completely/bogus/path/data.txt'
      mode = 'w'  # write mode
      
      try:
          dataFileObj = open( filename, mode )
          print('I just won the lottery!!!')
      except:
          print('ERROR! Unable to open', filename)
          sys.exit()
      
      print('Yeah,', filename, 'open successfully')
    2. Discuss with someone else the differences between print() and fileObject.write().
    3. Write a Python script that writes "Hello, world" to a file named "pythonOutput.txt". If an exception is thrown, display an error message to the user.
    4. Write a Python script that writes each letter of the alphabet on its own line to a file named "alphabet.txt". If an exception is thrown, display an error message to the user.
  7. Reading From and Writing To Files
    1. A bank has a text file called transactions.txt which has the transactions information for customers in the following format:
      Sarah Adams
      Deposit 
      350.00
      Withdraw 
      200.00
      Withdraw 
      50.00
      Deposit 
      150.00
      Deposit
      100.00
      Withdraw
      200.00
      Your task is to read the data from this file, calculate the resulting balance after all the transactions, and write customer's name and their updated balance in a new file called summary.txt:
      Sarah Adams: $150.00
    2. Write a Python script that reads in a file and sorts all of the words in the file and writes it out to another file.