LESSON 02 – WRITING TO A FILE

 


LESSON WORK

PROGRAM 1 – TENTH

Write a program that outputs every 10th numbers from 0 to 500 in a text file called “everyTen.txt”.

 

PROGRAM 2 – LEAP YEAR

Write a program that outputs every leap year starting at the year 1582 until now in a text file called “leapYear.txt”.  You will need to research the mathematical definition of a leap year.

 

PROGRAM 3 – HIGH SCORES

A text file contains a list of the top 5 high scores for a game.  Your job is to ask the use for their name and score and insert that into the list of high scores if the score is high enough. 

 

The file score.txt should look like this (though you can organize it any way you’d like):

Pat,424

Sandro,88

Kylie,79

Ryan,75

Dylan,63

Amber,61

 

SAMPLE OUTPUT 1

Enter your name
Jonah
Enter your score
53
Sorry, you are not in the top 5.

Here is the list of top 5 scores:

Pat 424

Sandro 88

Kylie 79

Ryan 75

Dylan 63

Amber 61

SAMPLE OUTPUT 2

Enter your name
Mikemeister
Enter your score

65
Congrats!  You are in the top 5!

Here is the list of top 5 scores:

Pat 424

Sandro 88

Kylie 79

Ryan 75

Mikemeister 65

Dylan 63

 

HINT:

You will have to read in the file one line at a time.  The split function will allow you to separate a line based on a separator (comma).

 

PROGRAM 4 – SPLITTER

Write the function called splitter that will read from a text file and copy all the content into two files splitting it such that all odd numbered characters go into one file and all even numbered characters go into the other file.

 

The function header should be:

 

            def splitter(src, dest1, dest2):

 

where

            src is a string holding the source’s filename

            dest1 is a string holding the first destination filename

            dest2 is a string holding the second destination filename

 

EXAMPLE

 

If the file source.txt contained the following:

 

            Hello world.  How are you?


then the function call

               splitter("source.txt", "dest1.txt", "dest2.txt")


will place

            Hlowrd o r o?


in the file dest1.txt, and


           
el ol.Hwaeyu


in the file dest2.txt.

 

 

PROGRAM 5 – MERGER

Write the program that will merge files created in the previous problem back into a single file.

 

The function header should be

            def merge(src1, src2, dest):

 

NOTE

 

After the following two function calls

 

splitter("source.txt", "dest1.txt", "dest2.txt")

merge ("dest1.txt", "dest2.txt", "merged.txt")

 

then the file merged.txt should be the same as source.txt.