# This program creates a file, adds data to the file, displays the file,
# appends more data to the file, displays the file, and then deletes the file.
# It will not run if the file already exists.
#
# References:
# https://www.mathsisfun.com/temperature-conversion.html
# https://en.wikibooks.org/wiki/Python_Programming
import os
import sys
def calculate_fahrenheit(celsius):
fahrenheit = celsius * 9 / 5 + 32
return fahrenheit
def create_file(filename):
try:
file = open(filename, "w")
file.write("Celsius,Fahrenheit\n")
for celsius in range(0, 51):
fahrenheit = calculate_fahrenheit(celsius)
file.write("{:.1f},{:.1f}\n".format(celsius, fahrenheit))
file.close()
except:
print("Error creating", filename)
print(sys.exc_info()[1])
def read_file(filename):
try:
file = open(filename, "r")
for line in file:
line = line.strip()
print(line)
file.close()
print()
except:
print("Error reading", filename)
print(sys.exc_info()[1])
def append_file(filename):
try:
file = open(filename, "a")
for celsius in range(51, 101):
fahrenheit = calculate_fahrenheit(celsius)
file.write("{:.1f},{:.1f}\n".format(celsius, fahrenheit))
file.close()
except:
print("Error appending to", filename)
print(sys.exc_info()[1])
def delete_file(filename):
try:
os.remove(filename)
except:
print("Error deleting", filename)
print(sys.exc_info()[1])
def main():
filename = "~file.txt"
if os.path.isfile(filename):
print("File already exists.")
else:
create_file(filename)
read_file(filename)
append_file(filename)
read_file(filename)
delete_file(filename)
main()