Persistence and File Output¶

CS 65: Introduction to Computer Science I¶

File Output¶

Most software that uses files allows you to both open (read from a file) and save files (write to a file).

This allows for persistence - when your programs keeps data in permanent storage.

  • Keep a historical record of rainfall and regularly add onto it
  • Database of employee wages - read from and make changes when necessary
  • Perform sentiment analysis on tons of movie reviews, and save the results to a file for later viewing
  • Save word scores for sentiment analysis to a file so you don't have to search the reviews every time you want to do sentiment analysis
  • Keep track of partial results for a simulation so if it gets interrupted, you don't lose your data, and you can continue executing where you left off

Python file output¶

In Python, we can use the open() function to open for either reading or writing. To overwrite a file, give the argument "w". To append to a file, give the argument "a".

In [1]:
def score_text(text):
    #pretend we're doing something real here
    return 2

review = "It was a breath of fresh air"
review_sentiment = score_text("It was a breath of fresh air")

with open("review_results.txt","a") as resultsfile:
    resultsfile.write(review+"; SENTIMENT SCORE:"+str(review_sentiment))

To actually write to the file, use the file's write() method.

  • Unlike print(), the write() method requires you to give it a string.
  • If you choose the "w" option, it will delete any previous version of the file with that name. Be careful!
  • If you don't want to delete what is already there, use "a" instead of "w"

Writing to CSV files¶

The csv module has a writer object that allows you to more easily write files in CSV format.

With the writer object, you can

  • write a single row with writerow()
  • write a whole 2D list with writerows()
In [2]:
import csv

parks_list = [["Name","Location","Year established","Area in acres"],
                ["Acadia National Park","Maine",1919,49076.63],
                ["National Park of American Samoa","American Samoa",1988,8256.67],
                ["Arches National Park","Utah",1971,76678.98]
                ]

with open("nationalparks_revised.csv","w") as parkfile:
    park_writer = csv.writer(parkfile)
    
    park_writer.writerows(parks_list)

Writing to JSON files¶

The json module provides a dumps() function which means dump to string which will convert a dictionary (or other campatible object) to a string. You can then write that string to a file using the normal file writing method.

In [3]:
import json

cs_dept_phonebook = {}

#open the json file
with open("cs_dept_phonebook.json") as cspbfile:
    cs_dept_phonebook = json.load(cspbfile)
    
print(cs_dept_phonebook)

#change the data
cs_dept_phonebook["Koonjbearry"] = "5557"

#save it back to the file with the same name
with open("cs_dept_phonebook.json","w") as cspbfile:
    cspbfile.write(json.dumps(cs_dept_phonebook))
{'Porter': '3041', 'Case': '4618', 'Klinge': '4599', 'Manley': '2177', 'Urness': '2118', 'Moore': '5555', 'Reza': '5556'}

Now we could open it again later and the new key-value pair is present.

In [4]:
import json

cs_dept_phonebook = {}

#open the json file
with open("cs_dept_phonebook.json") as cspbfile:
    cs_dept_phonebook = json.load(cspbfile)
    
print(cs_dept_phonebook)

#change the data
cs_dept_phonebook["Koonjbearry"] = "5557"

#save it back to the file with the same name
with open("cs_dept_phonebook.json","w") as cspbfile:
    cspbfile.write(json.dumps(cs_dept_phonebook))
{'Porter': '3041', 'Case': '4618', 'Klinge': '4599', 'Manley': '2177', 'Urness': '2118', 'Moore': '5555', 'Reza': '5556', 'Koonjbearry': '5557'}

Group Exercise¶

You created a function in Lab 17 which will compute the populations of each city within a state and store them in a dictionary. Let's re-use this function to create a program that will ask the user for a state and a JSON file name, and then save the city populations dictionary to the JSON file. It should behave like this:

city_pop_output.png