200 likes | 368 Views
Introduction to Files. CSIS 1595: Fundamentals of Programming and P roblem Solving 1. Files and Programs. Variables act as “link” to files Files can be opened in read , write , or append mode Write overwrites old file, append adds to end Text files consist of “string” of characters
E N D
Introduction to Files CSIS 1595: Fundamentals of Programming and Problem Solving 1
Files and Programs • Variables act as “link” to files • Files can be opened in read, write, or append mode • Write overwrites old file, append adds to end • Text files consist of “string” of characters • Characters read/written one at a time • Variable maintains “position” of program in file variable
Files and the OS • Files accessed via operating system • Operating system often buffers I/O for efficiency • Writes multiple characters to file once instead of one at a time when statement executed (efficiency) Program Input variable Output variable Operating System <<< data <<< >>> data >>> buffered data
Opening Files • Must open file before use • Get link to file via operating system • Syntax: variable = open(“filename”, mode) • By default in same directory as program • Mode: • “r”: read from file • “w”: write to file (overwriting previous contents • “a”: append to file (adding to end of previous contents)
Reading from Files • Simplest method: Use for to iterate through filefor stringvariable in filevariable:
Reading from Files • Each time through loop stringvariable assigned next entire line in file • All characters up to (and including) the \n • Often use strip function to remove extra \n from end Second time through loop Third time through loop First time through loop line
Writing to Files • Simplest method: Use modified form of print statementprint(string, file=“filevariable”) • Writes the string to the file (with \n at end) • Each print adds to end of last print
Closing Files • Should close file after using • Returns control of file to OS • Forces OS to write anything in buffer to file • Otherwise, no everything may actually be written to file! • Syntax: filevariable.close()
File Reading and Line Parsing • Often easier for humans to read file if multiple pieces of data on same line • Program must read in entire line as string • Then split line into component parts (split method) • Key: File must use some character to indicate split not used as part of data • Example: Comma Separated Values (CSV)
Program Design and Files • Common uses: • Processing contents of file to create result • Example: Computing sum of all numbers in file • May involve editing file in some way • Example: Removing duplicate names in file • Saving state of program • When program stopped, vital information saved • When program restarted, that information read back into variables • Example: Managing appointment list
Example: Computing Totals • Input: numbers.txt, containing floats • Possibly several per line separated by spaces • Goal: Print total of numbers in file • Algorithm: • Read each line into string, parse into list • Iterate through list, add to running total
Example: Removing Duplicates • Input: names.txt, containing names (one per line) • Output: no_duplicates.txt, containing same names with duplicates removed • Algorithm: • Keep list (initially empty) of all names read • For each name read in: • Use count to see if already in list (count of 0) • If not, add to list and write to file
State Storage • Goal: Store crucial program data between runs so user may “pick up” where they left off • Games • Text editors… • When program ends, store all necessary variables in file (probably one per line for simplicity) • Might also do after every change • Might also give user “save” command • When program restarts, read data from that file and store into those same variables • Might let user choose file
Appointment Book Example • Maintain list of “appointments” for times 0 – 9 • Create new appointment at a given time • Cancelappointment at a given time • Printall appointments • Internal representation: list • Must be able to save appointments between runs of the program • Prompt user for name of file at start • Write modified appointments at end to same file
Appointment Book Example • Often implement file read/write as functions • Call at beginning/end/when requested by user
Appointment Book Example • Key questions: • What program data must be stored List of appointments • How to store it One name per line in order
Appointment Book Example • Key questions: • What program data must be stored List of appointments • How to store it One name per line in order