110 likes | 284 Views
Files Access. 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
Files Access 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) • 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()
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