File Input/Output

This is Data Science. We care about data and a lot of our data will be stored in files, especially as we work on intro programming. Where else might data come from if not files? Databases. Web retrieval. Direct sensor connections. For today, we will learn the basics about reading and writing from files.

Reading: Chapter 7

Read Chapter 7 ... all of it.

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)

This program opens a text file of words and finds all names that follow "Dr. " to print them out.

fh = open('bigbook.txt')
fout = open('bigbook-names.txt','w')

for line in fh:
    line = line.lower()
    if "dr." in line:
        start = line.find("dr.")+4
        end = line.find(" ",start)
        name = line[start,end]
        fout.write(name + '\n')

fout.close()
fh.close()