CSC 171 - Introduction to Computer Programming

Lab Assignment #20 - Reading and Writing to a Text File

Due Wednesday, November 18, 2023

We have already seen how to open files for both input and output:

input_file = open("myfile.txt", "r")

output_file = open("yourfile.txt", "w")

We learned how to read the contents of a file in a for loop:

for inputLine in input_file:

        print(inputLine)

We also learned how to write in a file:

print(someStuff, file=output_file)

Remember that anything you read from a file is a character string - if you are reading numbers, you need to write:

myIntegerValue = int(inputLine) or

myFloatValue = float(inputLine)

We can write two line in that file by writing:

print("First line", file=my_file)
print("Second line", file=my_file)

After we finish using a file, it does not matter if it is for input or output, we write:
temp_file.close()

We have just learned that we can detect errors in our programs and exit gracefully:

fileNameStr = input("Open what file:")
try:
# potential user error
    input_file = open(fileNameStr)
    for xString in input_file:
        x = int(xString)
        print("The value is ", x)
    input_file.close()
except FileNotFoundError:
    print("The file doesn't exist.")
except ValueError:
    print(xString, " isn't a valid integer.")   

Write a program that reads a text file that contains one integer value per line. It will print each integer (one per line), the number of integers and their average. If one of the entries is not an integer, and print an appropriate message. Use try and except to handle errors gracefully.

[Back to the Lab Assignment List]