Lab 5: Files

The problems in this lab will help you understand reading and writing files.

Part 1: Reading and Writing a File

This part will help you understand reading and writing.

1.1. Open and Read a File

Create a file called ``test.txt`` with a few lines in it. Read and print the first line of the file. Don’t forget to close the file.

[ ]:

1.2. Read Two Lines

Wirte a program that reads the first two lines of test.txt and prints them. Don’t forget to close the file.

[ ]:

1.3. Write a File

Use Python to write the following into a file called fish.txt:

One fish,
Two fish,
Red fish,
Blue fish.

The program should create the file if it doesn’t exist.

[ ]:

1.4. Write Data

Write a program that uses the input() function to:

  • Ask the user for a file name (filename)

  • Ask the user for their name (word)

  • Ask the user for an integer (times)

Open the file filename then write word times number of times.

[ ]:

1.5. Append Data

Rewrite question the previous append data to the file instead of overwriting the file.

[ ]:

1.6. Read Lines and Reorder

Write a program that reads the four lines in fish.txt and prints them in reverse order.

[ ]: