Docstoc

files

Document Sample
files Powered By Docstoc
					CPS121 – Files Lab
Student Names: ______________________
Due: 10/31/2011

Objectives
   □ To begin working with files in Python.

Introduction:
In this lab, you will be given the opportunity to work with “real” data files that contain population data for some
towns in the US. There are all types of information contained in each town record: population, number of
households, average house value, and so forth (there is even the latitude and longitude of each town).

Part A: Getting Started
   1. Log on using the CPS121 account on the lab machine (password is Pythonia2011)
   2. Connect to one lab member‟s server share on Joshua. (Use the “Connect to Server menu option under
      the GO menu.) Create a “Lab8” folder. This storage area will be used to store files that are created
      during this lab.

Part B: Start a terminal window
In this lab, you will not be working with JES – instead you will be programming Python by using an operating
system terminal window. Within this terminal, you will be able to execute your programs.
    1. Go to the menu of the Finder application and use the menu option “Go” to go to the “Utilities”.
    2. Within this list of utilities – select and double-click “terminal.app”. This will start a “shell program”
         which will allow you to type commands.
    3. Here are 7 shell commands that are important with working within a terminal: ls, mkdir, rmdir, cd, rm,
         cat, & touch.

   Commands explained:
   ls – list the contents of a folder
   mkdir – make a folder within you current location
   rmdir – remove an empty folder
   cd – change your current location to another directory
   rm – remove a file
   touch – create an empty file
   cat - show the contents and create contents of a file

   Try out these commands:
   Enter “ls” at the terminal prompt – you should now see a list of all the files and directories that exist for
   the user “cps121”. If you enter “ls –l” you will see a more detailed listing of the files and directories.
   Enter “mkdir lab8” at the prompt – this creates a folder. Verify this fact using the ls command
   mentioned above.
   Enter “cd lab8” at the prompt – this will move your current location in the directory system into the
   newly created folder. Use “ls” – the folder should be empty. Use a command called “touch” – by entering
   “touch first”. Use the “ls” command – you should now have one file in the new folder. The touch
   command simply creates an empty file. Use touch to create a couple of more empty files. (Verify the
   existence of these files.)
    Enter “rm first” – this will remove (or delete) a file. Verify it.
    Enter “cat > first” – a blank line appears, type in a couple of lines of text. When you are done – hold the
    ctrl key and hit d. This will bring you back to the prompt. You have now created a file with some text –
    check this using the “ls –l” command. All the other files (other than first) should have a 0 in the column for
    size.
    Enter “cat first” – this will show the contents of the file you created.

    Repeat the above commands – creating a new folder called “test” which contains 3 files. One of the files
    should contain some lines.

    From within this new folder enter “ls –l”. Write down the information from this command here:




    From within this the “test” folder, enter “cd ..” – this will allow you to go back to the parent folder of
    “test”. Verify this by using “ls”.
    Enter “rm –r test” – this will delete the folder “test” and all the files within it. Please verify.
    Clean up the folder lab8 – eliminating all files within it.

Congratulations you are now a true Macintosh insider – there are many Mac owners but few who know
how to use Unix commands.

Part C: Start TextWrangler
You could create your lab program by using Unix commands – however you will be using a text editor called
“TextWrangler” instead. This is the easier way to create and edit your python programs.
   1. Go to the Dock that is located off the bottom of your computer screen. Select the application icon that is
      the “westernized W”. This will start TextWrangler. TextWrangler is a fairly basic file editor that allows
      you to create, edit, and save text files.
   2. Type the following Python program into the editor:
def generalMessage(text):
         print text

message = raw_input(“Enter a message to display: “)
generalMessage(message)
    3. Take a few moments to understand what the above program does
    4. Save it to the folder you create called “lab8” – call this new file “mess.py”

Part D: Use the Python interpreter to execute your new program
      Method 1: Direct Execution -
      Go back to your open terminal – navigate to the lab8 folder (on Desktop, in Documents?) if necessary.
      Enter “python mess.py” at the shell prompt. Complete the execution of this simple program by entering
      some message.
        Method 2: Import and Execute -
        Edit mess.py – delete the last 2 lines in the program. From within the lab8 folder – type in python at the
        command line (This will open up the python interpreter, which will allow you to enter commands into
        it). Enter “from mess import *” at the python prompt (>>>). Complete the execution of this simple
        program by entering: generalMessage(“Here it is”). This executes the python program from within the
        interpreter, which allows the programmer to execute a number of different commands along with the
        functions defined within the imported module.

        You have now learned everything you need to know to create and execute a python program from the
        terminal shell. It is time to create some programs that manipulate files.


Part E: File Download
         Type this URL (http://www.math-cs.gordon.edu/courses/cps121/labs/five000lines.csv) in a browser to
download the data file that will be used for lab today. The file contains the first 5000 records of a much larger
file that contains US census data. Note: Save this file within your lab8 folder.

Open the data file with TextWrangler to get an idea of how the file is organized and the kind of data that it
contains. Notice that the first record in the file contains the category names for the data contained in the other
records. Also, notice that each line has data separated by commas – this is known as a “comma separated” file.
This will mean that we will have to “split” each record in order to get each of the individual items in a line.
Also, notice that each piece of data is enclosed by quotes – these we can get rid of by using the “strip”
command.

Split practice:

    1. Type in “python” at the terminal.
    2. Type in this assignment statement: x = “4,5,6,7,8”
    3. Use the split command to obtain a list that looks like this: [„4‟,‟5‟,‟6‟,‟7‟,‟8‟]

        s.split([ separator[,maxsplit]])       Returns a list of the words in s, using separator as the delimiter
                                               string.

        Example: “cat:dog:eagle”.split(“:”) type this in to see what it does.

        Give your command:



Strip practice:

    1. Type in “python” at the terminal.
    2. Type in this assignment statement: x = „ “4,5,6,7,8” „
    3. Use the strip command to obtain a string that looks like this: „4,5,6,7,8‟

        s.strip([chars])                       Returns a copy of s with leading and trailing chars(default: blank
                                               chars) removed.
         Give your command:



Part F: Create a short program to create a simple file
   1. Type the following program into TextWrangler (replace comments with working statements):
def createFile():
         os.system("clear")
         filename = raw_input("Enter data filename: ")
         # place statement to open filename for writing
         # place statement to write one line to the file – write “Hello World”
         # place statement to close the file
         return

createFile()
    2.   Type “import os” at the very top of your program file (must be kept at the top)
    3.   Save the above program as lab8a.py within your new folder “lab8”
    4.   Execute the program by typing “python lab8a.py” in the terminal window (within lab8)
    5.   Use “ls” and “cat” to verify that the program creates the correct file.

Part G: Create a short program to read and display the first 25 zipcodes in the population file
   1. Type the following program into TextWrangler (replace comments with working statements):
def showTowns():
        os.system("clear")
        filename = raw_input("Enter data filename: ")
        # place statement to open filename for reading
        # place a statement to read off (and not use) the first line in the file
        # create a loop that will execute at least 25 times (should loop through at least 25 valid towns)
                 # read a line from the file (split and strip to get at the fields)
                 # if there is a code “P” (code “P” is the second field in the record) then it is a valid entry therefore
                           # display only the zipcode, town name and population

showTowns ()
    2.   Note: a code of “P” in the PrimaryRecord field means that it is contains useful data
    3.   Save the above program as lab8b.py within your new folder “lab8”
    4.   Execute the program by typing “python lab8b.py” in the terminal window (within lab8)
    5.   Verify that the results match the actual data in the file

Here‟s what the results show look like:
00501:         HOLTSVILLE,NY 0
00544:         HOLTSVILLE,NY 0
00601:         ADJUNTAS,PR 19143
00602:         AGUADA,PR 42042
00603:         AGUADILLA,PR 55530
00604:         AGUADILLA,PR 3923
00605:         AGUADILLA,PR 0
00606:         MARICAO,PR 6449
00610:         ANASCO,PR 27975
00611:         ANGELES,PR 0
00612:         ARECIBO,PR 72730
00613:      ARECIBO,PR 0
00614:      ARECIBO,PR 0
00616:      BAJADERO,PR 10532
00617:      BARCELONETA,PR 23370
00622:      BOQUERON,PR 8104
00623:      CABO ROJO,PR 38807
00624:      PENUELAS,PR 26719
00627:      CAMUY,PR 35244
00631:      CASTANER,PR 2188
00636:      ROSARIO,PR 0
00637:      SABANA GRANDE,PR 25935
00638:      CIALES,PR 19634
00641:      UTUADO,PR 35015
00646:      DORADO,PR 34099
00647:      ENSENADA,PR 5362

Part H: Create a short program to find the city, state with the largest IncomePerHousehold
   1. Type the following program into TextWrangler (replace comments with working statements):
def showLargest():
        os.system("clear")
        filename = raw_input("Enter data filename: ")
        # place statement to open filename for reading
        # place a statement to read off (and not use) the first line in the file
        # set the largest to 0
        # create a loop that iterates through the entire length of the file
                  # read a line from the file
                  # “split” and “strip” and turn it into an integer – compare this to the largest so far
                  # if new largest is found then save the town, state and amount


showLargest ()
    2. Save the above program as lab8c.py within your new folder “lab8”
    3. Execute the program by typing “python lab8c.py” in the terminal window (within lab8)
    4. Verify that the results match the actual data in the file

Show your results to the TA for verification. TA initial here____________________

Give Answer and Code:




Part H: Create a short program (lab8d.py) that creates the following file:

     The new file should contain only Mass towns – the file should have zipcode, town, state, population.
Remember to only use the records that have “P” for PrimaryRecord.

First few records in new file:
01001,AGAWAM,MA,16576
01002,AMHERST,MA,36794
01003,AMHERST,MA,0
01004,AMHERST,MA,0
01005,BARRE,MA,5077
01007,BELCHERTOWN,MA,13017
01008,BLANDFORD,MA,1235
01009,BONDSVILLE,MA,0




Give your code:




How many records does your file contain?




Lab Wrap-Up:
Place all your files and source code into a folder called lab8 on Joshua. Email a properly formatted coversheet
to the professor with the subject line: “CPS121 Lab8” + names.

				
DOCUMENT INFO
Shared By:
Categories:
Tags:
Stats:
views:16
posted:12/1/2011
language:English
pages:6