# Chapter7.py # text I/O -> page 206 # csv I/O -> page 216 # imports ## 2 Python Standard Modules import datetime # datetime Module import csv # csv Module to handle any comma seperated files # txt files are included in Python Core # file I/O -> I input O output # 3 commom ways to open an I/O ## 'w' -> write mode. Write mode ALWAYS overwrites the file. If the file exists, it will "delete" then "recreate" the file. If the file does not exit, it will create the file. ## 'a' -> append mode. Appends the data to the end of the file. If the file does not exist, it will create the file. Be aware of the end of line delimiter. Ex. txt files would require a line break to add a new line. csv files automatically have a line break. ## 'r' -> read more. Read mode handles the output of the file. Blocks any inputs ('w','a',...) # Level 2 os module -> When using an I/O to write to a directory, you can use either relative or absolute paths. These paths can be handled using the os module in python. # filename -> Entries_MMDDYYYY.txt ## Entries_MMDDYYYY.txt -> str + datetime + str ## 2 options to create the filename. Option 2 would be a best practice # option 1 -> create full string, convert datetime to string, format the datetime to MMDDYYYY Python filename1 = "Entries_" + str(datetime.datetime.now().strftime("%m%d%Y")) + ".txt" print(filename1) # Entries_11212024.txt # option 2 Pythonic stringDateTime = str(datetime.datetime.now().strftime("%m%d%Y")) filename2 = "Entries_" + stringDateTime + ".txt" print(filename2) # Entries_11212024.txt # Ask the user to enter their first name and last name as strings, and add their age as integer. Then, create a variable called "data" that will look like "First Name: Bob Last Name: Smith Age: 21 Date Entered: 11/21/2024." first_name = input("Enter your first name: ") last_name = input("Enter your last name: ") age = int(input("Enter your age: ")) dataDateTime = str(datetime.datetime.now().strftime("%m/%d/%Y")) data = f"First Name: {first_name} Last Name: {last_name} Age: {age} Date Entered: {dataDateTime}." print(data) # Write the data to the file using the "with" and the "as" keywords # open() function can either be used by itself or using the "with" keyword, which is recommended. # IF you DO NOT use the "with" keyword, the I/O WILL NOT close itself, you will need to MANUALLY close the I/O. # The "with" keyword AUTOMATICALLY closes stream when the function is done, NOT when the program closes. with open(filename2,'a') as file: # as file creates a local variable for the stream, so you can use it in the suboperations / scope of the function buffer = data + "\n" file.write(buffer) # pass ok to get to the next line confirmed = f"The {filename2} was updated with {first_name}'s data successfully." print(confirmed) # The Entries_11212024.txt was updated with Marcus's data successfully. print(f"##### Data in {filename2} #####") print("-------------------------------") # Read the data in an I/O to a buffer, then output using print() with open(filename2, 'r') as file: # read the data to a buffer buffer = file.read() # read the entire file to the buffer. print(buffer) ''' First Name: Bob Last Name: Smith Age: 21 Date Entered: 11/21/2024. First Name: Mary Last Name: Jones Age: 45 Date Entered: 11/21/2024. First Name: Harry Last Name: Johnson Age: 62 Date Entered: 11/21/2024. First Name: Marcus Last Name: Jones Age: 21 Date Entered: 11/21/2024. First Name: Beth Last Name: Johnson Age: 45 Date Entered: 11/21/2024. ''' print("#### csv module example ####") print("----------------------------") # csv files needs import csv # Python Standard Module that needs to be imported csvfile = 'contacts.csv' with open(csvfile, 'a', newline='') as file: # headers fieldnames = ['FirstName','LastName','Age','DateEntered'] # buffer buffer = csv.DictWriter(file,fieldnames=fieldnames) if file.tell() == 0: buffer.writeheader() # looks for the fieldnames attr in the writer and if it does not exist, write the header # write the data rows buffer.writerow( { 'FirstName': first_name, # col A 'LastName': last_name, # col B 'Age': age, # col C 'DateEntered': dataDateTime # col D } ) # buffer confirmed = f"The {csvfile} was updated with {first_name}'s data successfully." print(confirmed) # The contacts.csv was updated with Marcus's data successfully. # EOF Chapter7.py