# basic txt file and write data to that file open() # Chapter 4 page 45 and 46 from datetime import datetime def basictxtfile(): # write data to a file file = open("contacts.txt", "a") file.write("Philip\n") file.close() # close() is required for flat file txt # read the lines in the file file = open("contacts.txt", "r") print(file.read()) # open() function with a variable name def txtfile(): filename = "contacts.txt" file = open(filename, "a") file.write("Bob\n") file.close() # close() is required for flat file txt # read the lines in the file file = open(filename, "r") print(file.read()) # open() function with a variable name dynamic data from input() def txtfilewithinput(): filename = "contacts.txt" file = open(filename, "a") #file.write("Bob\n") data = input("Enter a new contact: ") stringdata = data + "\n" file.write(stringdata) file.close() # close() is required for flat file txt # read the lines in the file file = open(filename, "r") print(file.read()) # open() function with a variable name dynamic data from input() with a timestamp on the new contact line def txtfilewithinputandtimestamp(): filename = "contacts.txt" file = open(filename, "a") #file.write("Bob\n") data = input("Enter a new contact: ") # datetime Module datetime Class from datetime import datetime # from MODULENAME import ClassName currenttime = datetime.now() stringdata = data + "," + str(currenttime) + "\n" file.write(stringdata) file.close() # close() is required for flat file txt # read the lines in the file file = open(filename, "r") print(file.read()) # open() function with a variable name dynamic data from input() with a timestamp on the new contact line using a structured file (csv) # contacts.csv # fname, timestamp header row[0] # data rows[1:] # fname[col1], timestamp[col2] def contactscsv(): # csv module is a Standard Library import keyword import csv # Create an empty list in memory contactInfo = [] # Variable to assign the filename to filename = "contacts.csv" # Open the csv file and read the rows, append to the list in memory with open(filename) as csv_file: # csv_file is an object # read the rows rows_reader = csv.reader(csv_file, delimiter=",") # loop thru the rows for row in rows_reader: contactInfo.append(row) # append each row to the list in memory print(contactInfo) print() print("=== Formatted Data ===") headerrow = contactInfo[0] datarows = contactInfo[1:] print(headerrow) print("-----------") print(datarows) print("=== EOL ===") # Contact Entry Form fname = input("Enter Contact First Name: ") currenttime = str(datetime.now()) # string cast of datetime.now() # print(fname + " " + currenttime) # Write the new row to the csv object with open(filename, 'a', newline='') as csv_file: # Map for the column names csvcolumnnames = ['fname','timestamp'] # key:value pairs for the row datarow = csv.DictWriter(csv_file, fieldnames=csvcolumnnames) datarow.writerow({'fname': fname, 'timestamp': currenttime}) # EOF