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.
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".
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.
print(), the write() method requires you to give it a string."w" option, it will delete any previous version of the file with that name. Be careful!"a" instead of "w"The csv module has a writer object that allows you to more easily write files in CSV format.
With the writer object, you can
writerow()writerows()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)
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.
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))
Now we could open it again later and the new key-value pair is present.
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))
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: