# Chapter7.py chapter7.py # File Input/Output I/O IO ## txt -> Python Core print() int() str() input() ## csv -> Python Standard ### import csv ### from csv import objectName ### import csv as nameSpace/alias ### all other file types -> pip install module Level 2/3 ## Both the txt and csv use the open() ## open() Python Core -> file I/O ## txt files have to be MANUALLY closed with close() ## csv files have a natural close() # Open a txt file using the with keyword and the open() function # 3 common modes ## 'r' -> read a file, if the file does NOT exist, it will throw a File Not Found error ## 'w' -> write to a file, this is an overwrite. If the file does NOT exist, it will create it, then write the data ## 'a' -> appends the new data to the end of the file. If the file does NOT exist, it will create the file and write the data ## mode='a' attr='value' internal attr to the open() ### open('filename.txt', mode='a') ## append() -> appends to the end of the obj, as a pipe ## 'with' keyword will always have an 'as' keyword ### with open() as alias # data validation ## web app client side -> javascript? ## desktop -> regular expressions (level 2) ## if statement to test the input ## state with only 2 chars if len(state) == 2 ## database field ONLY accepts 5 char -> what to test on the client side BEFORE write database def isEmailValid(): pass def isPhoneValid(): pass filename = 'myContacts.txt' with open(filename, 'a') as file: # inside this with scope, myContacts.txt is defined as 'file' # all IO they will have reader() and writer()/ read() write() contact = input("Enter contact full name: ") file.write(contact + '\n') print(f"Contact: {contact} successfully written to {file}.") file.close() ''' userMode = input("How do you want to open the file (r->read,a->append,w->write)") paramMode = f"'{userMode}'" open(filename, paramMode) ''' # Read the new data using the read() with open(filename, 'r') as file: # Read all data into the variable in memory content = file.read() print(content) file.close() print("---------------------") # csv Module import csv csvfile = 'contacts.csv' rows = [] # List to handle any data sets print(rows) # empty with open(csvfile) as f: # no mode assumes 'r' csv_reader = csv.reader(f,delimiter=',') for row in csv_reader: rows.append(row) # append each row from the reader to a list named rows print(rows) # data from the reader headerrow = rows[0] # rows are indexed 1st row is [0] datarows = rows[1:] # [start:end] print("Date from the CSV File") print("-----------------------") print(headerrow) print(datarows)