CPSC120A
Fundamentals of Computer Science I

Activity 26

File I/O.

File I/O

Python provides multiple ways of reading a file. Each method is suited to different purposes. In this activity you will explore some of the differences.


For each of the following, what would the program print if run? Assume that the file in.txt has the following contents:

1
2
3
  1. input_file = open('in.txt', 'r')
    for line in input_file:
        print(line)
    input_file.close()
    
  2. input_file = open('in.txt', 'r')
    for line in input_file:
        print(line.strip())
    input_file.close()
    
  3. input_file = open('in.txt', 'r')
    line_list = input_file.readlines()
    print(line_list)
    input_file.close()
    
  4. input_file = open('in.txt', 'r')
    line_string = input_file.read()
    line_list = line_string.split('\n')
    print(line_list)
    input_file.close()