Files and Data

Today we pause on introducing new programming tools and talk about how to ingest data from files. As you've seen in a couple labs now, reading in lines from text files is pretty simple. Today we'll dive a little deeper into that, and make sure we're comfortable with input, as well as show how to write to new files.

Reading: Chapter 4

Please read Chapter 7 on Files.

Today in Class

We will discuss and learn about:

You should be able to understand these programs.

This program opens a text file that has integers one per line. It prints their sum:

sum = 0
fh = open('numbers.txt')
for line in fh:
    sum = sum + int(line)
print("File numbers sum =", sum)

Let's open a file of integers, and then create a new file of just the prime numbers we find:

def isprime(num):
    """ Returns true if the given num is prime """
    if num <= 1:
        return False
    
    for i in range(2, int(num/2)+1):
        if num % i == 0:
            return False
        
    return True    # If we reached here, then no divisor was found.

# Open a file of integers (one per line)
fh = open('numbers.txt')
primes = []
for line in fh:
    if isprime(int(line)):
        primes.append(int(line))

# Write to a new file only the primes.        
fout = open('primes.txt', 'w')        
for prime in primes:
    fout.write(str(prime) + ' ')
fout.close()