Lecture5_File_Handling_Python.pptx

Full Transcript

Introduction to File Handling Overview of Object-Oriented Programming (OOP) and file handling in C# and Python. What is OOP? Object-Oriented Programming is a paradigm based on the concept of objects, which can contain data and methods. Core Principles of OOP Encapsula...

Introduction to File Handling Overview of Object-Oriented Programming (OOP) and file handling in C# and Python. What is OOP? Object-Oriented Programming is a paradigm based on the concept of objects, which can contain data and methods. Core Principles of OOP Encapsulation is the bundling of data and methods that operate on the data within one unit, e.g., a class in C# and Python. Abstraction is the concept of hiding the complex implementation details and showing only the necessary features. Inheritance is a mechanism where a new class is derived from an existing class. Polymorphism is the ability of a function, method, or object to take on multiple forms. File Handling and OOP Combining file handling with OOP involves creating classes and objects that encapsulate file operations. Data Files It contains data pertaining to a specific application, for later. The data files can be stored in two ways – Text File – Binary File Text File Text files store information in ASCII OR UNICODE characters. In a text file, everything will be stored as a character. – For example, if the data is “computer”, it will take 8 bytes; if the data is a floating value like 11237.9876, it will take 10 bytes. In the text file, each line is terminated by a special character called EOL. When this EOL character is read or written, some translation takes place. In python, EOL is ‘\n’ or ‘\r’ or a combination of both. Steps in Data File Handling Opening File – We should first open the file for reading or writing by specifying the name of the file and mode. – Performing Read/Write – Once the file is open, you can either read or write to the open file using various functions available. File Handling in C# File handling involves reading and writing data to and from files. – In C#, this is done using System.IO namespace. – In Python, the io module serves as the overarching module that contains classes and functions for handling I/O operations Python provides built-in modules like os and io that offer functionality for reading from and writing to files and data streams. Example of reading a text file using Python – use the open function. What You Need In Order To Read Information From A File 1. Open the file and associate the file with a file variable. 2. A command to read the information. 3. A command to close the file. Opening File File can be opened for either-read, write, apend Syntax: File_object=open(filename) Or File_object=open(filename,mode) Opening File # Reading a file with open("file.txt", "r") as file: content = file.read() # Writing to a file with open("file.txt", "w") as file: file.write("Hello, World!") #Close the file file.close() File mode 1.Opening Files Prepares the file for reading: A. Links the file variable with the physical file (references to the file variable are references to the physical file). B. Positions the file pointer at the start of the file. Format:1 = open(, "r") Example: (Constant file name) inputFile = open("data.txt", "r") OR (Variable file name: entered by user at runtime) filename = input("Enter name of input file: ") inputFile = open(filename, "r") 1 Examples assume that the file is in the same directory/folder as the Python program. B.Positioning The File Pointer letters.txt A B C B B : 2.Reading Information From Files Typically reading is done within the body of a loop Each execution of the loop will read a line from the file into a string Format: for in : Example: for line in inputFile: print(line) # Display file contents back on the screen Closing The File Format:.close() Example: inputFile.close() Error Handling With Exceptions Exceptions are used to deal with extraordinary errors (‘exceptional ones’). Typically these are fatal runtime errors (“crashes” program) Example: trying to open a non-existent file Basic structure of handling exceptions try: Attempt something where exception error may happen except : React to the error else: # Not always needed What to do if no error is encountered finally: # Not always needed Actions that must always be performed Exceptions: File Example Name of the online example: file_exception.py Input file name: Most of the previous input files can be used e.g. “ input1.txt” inputFileOK = False while (inputFileOK == False): try: inputFileName = input("Enter name of input file: ") inputFile = open(inputFileName, "r") except IOError: print("File", inputFileName, "could not be opened") else: print("Opening file", inputFileName, " for reading.") inputFileOK = True for line in inputFile: sys.stdout.write(line) print ("Completed reading of file", inputFileName) inputFile.close() print ("Closed file", inputFileName) Exceptions: File Example (2) # Still inside the body of the while loop (continued) finally: if (inputFileOK == True): print ("Successfully read information from file", inputFileName) else: print ("Unsuccessfully attempted to read information from file", inputFileName) You Should Now Know How to open a file for reading How to open a file a file for writing The details of how information is read from and written to a file How to close a file and why it is a good practice to do this explicitly How to read from a file of arbitrary size Data storage and processing using files and string functions How exceptions can be used in conjunction with file input and with invalid keyboard/console input import io class LoggingFile (io.TextIOWrapper): def write(self, data): print(f"Writing data: {data}") # Log the data being written super().write(data) # Call the original write method # Usage with open('example.txt', 'w') as file: logged_file = LoggingFile(file) logged_file.write("Hello, world!\n") logged_file.write("Another line.\n") logged_file.close() Inheritance io Module: Provides foundational classes for working with various types of I/O in Python, such as text and binary streams. Inheritance: By inheriting from classes in the io module (like io.TextIOWrapper), you can create custom file-like objects that extend or modify the behavior of standard file operations. Customization: Inheritance allows you to override methods like read() and write() to add additional functionality (e.g., logging, encryption, etc.) while still leveraging the robust features of the io module. Advanced File Operations Advanced operations include file encryption, compression, and using asynchronous file handling. (Last Unit) Conclusion Understanding file handling within the OOP paradigm is crucial for building robust applications. Test solutions 1.Opening The File Format1: = open(, "w") Example: (Constant file name) outputFile = open("gpa.txt", "w") (Variable file name: entered by user at runtime) outputFileName = input("Enter the name of the output file to record the GPA's to: ") outputFile = open(outputFileName, "w") 1 Typically the file is created in the same directory/folder as the Python program. 3.Writing To A File You can use the ‘write()’ function in conjunction with a file variable. Note however that this function will ONLY take a string parameter (everything else must be converted to this type first). Format: outputFile.write(temp) Example: # Assume that temp contains a string of characters. outputFile.write (temp) Writing To A File: Putting It All Together Name of the online example: grades2.py Input file: “letters.txt” (sample output file name: gpa.txt) inputFileName = input("Enter the name of input file to read the grades from: ") outputFileName = input("Enter the name of the output file to record the GPA's to: ") inputFile = open(inputFileName, "r") outputFile = open(outputFileName, "w") print("Opening file", inputFileName, " for reading.") print("Opening file", outputFileName, " for writing.") gpa = 0 Writing To A File: Putting It All Together (2) for line in inputFile: if (line == "A"): gpa = 4 elif (line == "B"): gpa = 3 elif (line == "C"): gpa = 2 elif (line == "D"): gpa = 1 elif (line == "F"): gpa = 0 else: gpa = -1 temp = str (gpa) temp = temp + '\n' print (line, '\t', gpa) outputFile.write (temp) Writing To A File: Putting It All Together (3) inputFile.close () outputFile.close () print ("Completed reading of file", inputFileName) print ("Completed writing to file", outputFileName) Example to write to a file Extra Reading From Files: Commonly Used Algorithm Pseudo-code: Read a line from a file as a string While (string is not empty) process the line Read another line from the file File Input: Alternate Implementation Name of the online example: grades3.py inputFileName = input ("Enter name of input file: ") inputFile = open(inputFileName, "r") print("Opening file", inputFileName, " for reading.") line = inputFile.readline() while (line != ""): sys.stdout.write(line) line = inputFile.readline() inputFile.close() print("Completed reading of file", inputFileName) Data Processing: Files Files can be used to store complex data given that there exists a predefined format. Format of the example input file: ‘employees.txt’ ,, Example Program: data_processing.py # EMPLOYEES.TXT Adama Lee,CAG,30000 Morris Heather,Heroine,0 inputFile = open ("employees.txt", "r") Lee Bruce,JKD master,100000 print ("Reading from file input.txt") for line in inputFile: name,job,income = line.split(',') last,first = name.split() income = int(income) income = income + (income * BONUS) print("Name: %s, %s\t\t\tJob: %s\t\tIncome $%.2f" %(first,last,job,income)) print ("Completed reading of file input.txt") inputFile.close()

Use Quizgecko on...
Browser
Browser